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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .8(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.118.2.7 2020/09/08 02:08:27 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='';
                   8440:20): # List of blocks passed to &get_commblock_resources();
                   8441:20): my $cachedblocks='';
1.1172.2.66  raeburn  8442: # Cached blockers for this user (a hash of blocking items).
                   8443: my %cachedblockers=();
                   8444: # When the data were last cached.
                   8445: my $cachedlast='';
                   8446: 
                   8447: sub load_all_blockers {
                   8448:     my ($uname,$udom,$blocks)=@_;
                   8449:     if (($uname ne '') && ($udom ne '')) {
                   8450:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8451:20):             ($cachedcid eq $env{'request.course.id'}) &&
                   8452:20):             (abs($cachedlast-time)<5) &&
                   8453:20):             (((ref($blocks) eq 'HASH') &&
                   8454:20):               ($cachedblocks eq join(',',sort(keys(%{$blocks}))))) ||
                   8455:20):              (!ref($blocks) && $cachedblocks eq ''))) {
1.1172.2.66  raeburn  8456:             return;
                   8457:         }
                   8458:     }
                   8459:     $cachedlast=time;
                   8460:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8461:20):     $cachedcid=$env{'request.course.id'};
1.1172.2.66  raeburn  8462:     %cachedblockers = &get_commblock_resources($blocks);
1.1172.2.118.  .8(raebu 8463:20):     if ((ref($blocks) eq 'HASH') && (keys(%{$blocks}) > 0)) {
                   8464:20):         $cachedblocks = join(',',sort(keys(%{$blocks})));
                   8465:20):     }
                   8466:20):     return;
1.1172.2.66  raeburn  8467: }
                   8468: 
1.1162    raeburn  8469: sub get_comm_blocks {
                   8470:     my ($cdom,$cnum) = @_;
                   8471:     if ($cdom eq '' || $cnum eq '') {
                   8472:         return unless ($env{'request.course.id'});
                   8473:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8474:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8475:     }
                   8476:     my %commblocks;
                   8477:     my $hashid=$cdom.'_'.$cnum;
                   8478:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8479:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8480:         %commblocks = %{$blocksref};
                   8481:     } else {
                   8482:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8483:         my $cachetime = 600;
                   8484:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8485:     }
                   8486:     return %commblocks;
                   8487: }
                   8488: 
1.1172.2.66  raeburn  8489: sub get_commblock_resources {
                   8490:     my ($blocks) = @_;
                   8491:     my %blockers = ();
                   8492:     return %blockers unless ($env{'request.course.id'});
                   8493:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8494:     my %commblocks;
                   8495:     if (ref($blocks) eq 'HASH') {
                   8496:         %commblocks = %{$blocks};
                   8497:     } else {
                   8498:         %commblocks = &get_comm_blocks();
                   8499:     }
1.1172.2.66  raeburn  8500:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8501:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8502:     return %blockers unless (ref($navmap));
                   8503:     my $now = time;
1.1162    raeburn  8504:     foreach my $block (keys(%commblocks)) {
                   8505:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8506:             my ($start,$end) = ($1,$2);
                   8507:             if ($start <= $now && $end >= $now) {
                   8508:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8509:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8510:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8511:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8512:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8513:                             }
                   8514:                         }
                   8515:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8516:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8517:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8518:                             }
                   8519:                         }
                   8520:                     }
                   8521:                 }
                   8522:             }
                   8523:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8524:             my $item = $1;
1.1163    raeburn  8525:             my @to_test;
1.1162    raeburn  8526:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8527:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8528:                     my @interval;
                   8529:                     my $type = 'map';
                   8530:                     if ($item eq 'course') {
                   8531:                         $type = 'course';
                   8532:                         @interval=&EXT("resource.0.interval");
                   8533:                     } else {
                   8534:                         if ($item =~ /___\d+___/) {
                   8535:                             $type = 'resource';
                   8536:                             @interval=&EXT("resource.0.interval",$item);
                   8537:                             if (ref($navmap)) {
                   8538:                                 my $res = $navmap->getBySymb($item);
                   8539:                                 push(@to_test,$res);
                   8540:                             }
1.1162    raeburn  8541:                         } else {
1.1172.2.66  raeburn  8542:                             my $mapsymb = &symbread($item,1);
                   8543:                             if ($mapsymb) {
                   8544:                                 if (ref($navmap)) {
                   8545:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8546:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8547:                                     foreach my $res (@to_test) {
                   8548:                                         my $symb = $res->symb();
                   8549:                                         next if ($symb eq $mapsymb);
                   8550:                                         if ($symb ne '') {
                   8551:                                             @interval=&EXT("resource.0.interval",$symb);
                   8552:                                             if ($interval[1] eq 'map') {
                   8553:                                                 last;
1.1162    raeburn  8554:                                             }
                   8555:                                         }
                   8556:                                     }
                   8557:                                 }
                   8558:                             }
                   8559:                         }
1.1172.2.66  raeburn  8560:                     }
1.1172.2.118.  .1(raebu 8561:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8562:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8563:                         my $first_access;
                   8564:                         if ($type eq 'resource') {
                   8565:                             $first_access=&get_first_access($interval[1],$item);
                   8566:                         } elsif ($type eq 'map') {
                   8567:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8568:                         } else {
                   8569:                             $first_access=&get_first_access($interval[1]);
                   8570:                         }
                   8571:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8572:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8573:                             if ($timesup > $now) {
                   8574:                                 my $activeblock;
                   8575:                                 foreach my $res (@to_test) {
                   8576:                                     if ($res->answerable()) {
                   8577:                                         $activeblock = 1;
                   8578:                                         last;
                   8579:                                     }
                   8580:                                 }
                   8581:                                 if ($activeblock) {
                   8582:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8583:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8584:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8585:                                          }
                   8586:                                     }
                   8587:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8588:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8589:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8590:                                         }
1.1162    raeburn  8591:                                     }
                   8592:                                 }
                   8593:                             }
                   8594:                         }
                   8595:                     }
                   8596:                 }
                   8597:             }
                   8598:         }
                   8599:     }
1.1172.2.66  raeburn  8600:     return %blockers;
1.1162    raeburn  8601: }
                   8602: 
1.1172.2.66  raeburn  8603: sub has_comm_blocking {
1.1172.2.118.  .8(raebu 8604:20):     my ($priv,$symb,$uri,$nosymbcache,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8605:     my @blockers;
                   8606:     return unless ($env{'request.course.id'});
                   8607:     return unless ($priv eq 'bre');
                   8608:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8609:     return if ($env{'request.state'} eq 'construct');
                   8610:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8611:     return unless (keys(%cachedblockers) > 0);
                   8612:     my (%possibles,@symbs);
                   8613:     if (!$symb) {
1.1172.2.118.  .8(raebu 8614:20):         $symb = &symbread($uri,1,1,1,\%possibles,$nosymbcache,$noenccheck);
1.1162    raeburn  8615:     }
1.1172.2.66  raeburn  8616:     if ($symb) {
                   8617:         @symbs = ($symb);
                   8618:     } elsif (keys(%possibles)) {
                   8619:         @symbs = keys(%possibles);
                   8620:     }
                   8621:     my $noblock;
                   8622:     foreach my $symb (@symbs) {
                   8623:         last if ($noblock);
                   8624:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8625:         foreach my $block (keys(%cachedblockers)) {
                   8626:             if ($block =~ /^firstaccess____(.+)$/) {
                   8627:                 my $item = $1;
1.1172.2.118.  .8(raebu 8628:20):                 unless ($blocked) {
                   8629:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8630:20):                         $noblock = 1;
                   8631:20):                         last;
                   8632:20):                     }
1.1172.2.66  raeburn  8633:                 }
1.1162    raeburn  8634:             }
1.1172.2.66  raeburn  8635:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8636:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8637:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8638:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8639:                             push(@blockers,$block);
                   8640:                         }
                   8641:                     }
                   8642:                 }
1.1172.2.118.  .8(raebu 8643:20):                 if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8644:20):                     if ($cachedblockers{$block}{'maps'}{$map}) {
                   8645:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8646:20):                             push(@blockers,$block);
                   8647:20):                         }
1.1172.2.66  raeburn  8648:                     }
                   8649:                 }
1.1162    raeburn  8650:             }
                   8651:         }
                   8652:     }
1.1172.2.118.  .8(raebu 8653:20):     unless ($noblock) {
                   8654:20):         return @blockers;
                   8655:20):     }
                   8656:20):     return;
1.1172.2.66  raeburn  8657: }
1.1162    raeburn  8658: }
                   8659: 
1.1172.2.66  raeburn  8660: # -------------------------------- Deversion and split uri into path an filename
                   8661: 
1.1133    foxr     8662: #
1.1172.2.66  raeburn  8663: #   Removes the version from a URI and
1.1133    foxr     8664: #   splits it in to its filename and path to the filename.
                   8665: #   Seems like File::Basename could have done this more clearly.
                   8666: #   Parameters:
                   8667: #      $uri   - input URI
                   8668: #   Returns:
                   8669: #     Two element list consisting of 
                   8670: #     $pathname  - the URI up to and excluding the trailing /
                   8671: #     $filename  - The part of the URI following the last /
                   8672: #  NOTE:
                   8673: #    Another realization of this is simply:
                   8674: #    use File::Basename;
                   8675: #    ...
                   8676: #    $uri = shift;
                   8677: #    $filename = basename($uri);
                   8678: #    $path     = dirname($uri);
                   8679: #    return ($filename, $path);
                   8680: #
                   8681: #     The implementation below is probably faster however.
                   8682: #
1.710     albertel 8683: sub split_uri_for_cond {
                   8684:     my $uri=&deversion(&declutter(shift));
                   8685:     my @uriparts=split(/\//,$uri);
                   8686:     my $filename=pop(@uriparts);
                   8687:     my $pathname=join('/',@uriparts);
                   8688:     return ($pathname,$filename);
                   8689: }
1.232     www      8690: # --------------------------------------------------- Is a resource on the map?
                   8691: 
                   8692: sub is_on_map {
1.710     albertel 8693:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8694:     #Trying to find the conditional for the file
1.620     albertel 8695:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8696: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8697:     if ($match) {
1.289     bowersj2 8698: 	return (1,$1);
                   8699:     } else {
1.434     www      8700: 	return (0,0);
1.289     bowersj2 8701:     }
1.12      www      8702: }
                   8703: 
1.427     www      8704: # --------------------------------------------------------- Get symb from alias
                   8705: 
                   8706: sub get_symb_from_alias {
                   8707:     my $symb=shift;
                   8708:     my ($map,$resid,$url)=&decode_symb($symb);
                   8709: # Already is a symb
                   8710:     if ($url) { return $symb; }
                   8711: # Must be an alias
                   8712:     my $aliassymb='';
                   8713:     my %bighash;
1.620     albertel 8714:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8715:                             &GDBM_READER(),0640)) {
                   8716:         my $rid=$bighash{'mapalias_'.$symb};
                   8717: 	if ($rid) {
                   8718: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8719: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8720: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8721: 	}
                   8722:         untie %bighash;
                   8723:     }
                   8724:     return $aliassymb;
                   8725: }
                   8726: 
1.12      www      8727: # ----------------------------------------------------------------- Define Role
                   8728: 
                   8729: sub definerole {
                   8730:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8731:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8732:     foreach my $role (split(':',$sysrole)) {
                   8733: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8734:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8735:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8736: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8737:                return "refused:s:$crole&$cqual"; 
                   8738:             }
                   8739:         }
1.191     harris41 8740:     }
1.800     albertel 8741:     foreach my $role (split(':',$domrole)) {
                   8742: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8743:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8744:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8745: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8746:                return "refused:d:$crole&$cqual"; 
                   8747:             }
                   8748:         }
1.191     harris41 8749:     }
1.800     albertel 8750:     foreach my $role (split(':',$courole)) {
                   8751: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8752:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8753:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8754: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8755:                return "refused:c:$crole&$cqual"; 
                   8756:             }
                   8757:         }
1.191     harris41 8758:     }
1.1172.2.84  raeburn  8759:     my $uhome;
                   8760:     if (($uname ne '') && ($udom ne '')) {
                   8761:         $uhome = &homeserver($uname,$udom);
                   8762:         return $uhome if ($uhome eq 'no_host');
                   8763:     } else {
                   8764:         $uname = $env{'user.name'};
                   8765:         $udom = $env{'user.domain'};
                   8766:         $uhome = $env{'user.home'};
                   8767:     }
1.620     albertel 8768:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8769:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8770:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8771:     return reply($command,$uhome);
1.12      www      8772:   } else {
                   8773:     return 'refused';
                   8774:   }
1.105     harris41 8775: }
                   8776: 
                   8777: # ---------------- Make a metadata query against the network of library servers
                   8778: 
                   8779: sub metadata_query {
1.1172.2.33  raeburn  8780:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8781:     my %rhash;
1.845     albertel 8782:     my %libserv = &all_library();
1.244     matthew  8783:     my @server_list = (defined($server_array) ? @$server_array
                   8784:                                               : keys(%libserv) );
                   8785:     for my $server (@server_list) {
1.1172.2.33  raeburn  8786:         my $domains = '';
                   8787:         if (ref($domains_hash) eq 'HASH') {
                   8788:             $domains = $domains_hash->{$server};    
                   8789:         }
1.118     harris41 8790: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8791: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8792: 	    $rhash{$server}=$reply;
                   8793: 	}
                   8794: 	else {
                   8795: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8796: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8797: 			     $server);
                   8798: 	    $rhash{$server}=$reply;
                   8799: 	}
1.112     harris41 8800:     }
1.118     harris41 8801:     return \%rhash;
1.240     www      8802: }
                   8803: 
                   8804: # ----------------------------------------- Send log queries and wait for reply
                   8805: 
                   8806: sub log_query {
                   8807:     my ($uname,$udom,$query,%filters)=@_;
                   8808:     my $uhome=&homeserver($uname,$udom);
                   8809:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8810:     my $uhost=&hostname($uhome);
1.800     albertel 8811:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8812:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8813:                        $uhome);
1.479     albertel 8814:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8815:     return get_query_reply($queryid);
                   8816: }
                   8817: 
1.818     raeburn  8818: # -------------------------- Update MySQL table for portfolio file
                   8819: 
                   8820: sub update_portfolio_table {
1.821     raeburn  8821:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8822:     if ($group ne '') {
                   8823:         $file_name =~s /^\Q$group\E//;
                   8824:     }
1.818     raeburn  8825:     my $homeserver = &homeserver($uname,$udom);
                   8826:     my $queryid=
1.821     raeburn  8827:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8828:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8829:     my $reply = &get_query_reply($queryid);
                   8830:     return $reply;
                   8831: }
                   8832: 
1.899     raeburn  8833: # -------------------------- Update MySQL allusers table
                   8834: 
                   8835: sub update_allusers_table {
                   8836:     my ($uname,$udom,$names) = @_;
                   8837:     my $homeserver = &homeserver($uname,$udom);
                   8838:     my $queryid=
                   8839:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8840:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8841:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8842:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8843:                'generation='.&escape($names->{'generation'}).'%%'.
                   8844:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8845:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8846:     return;
1.899     raeburn  8847: }
                   8848: 
1.508     raeburn  8849: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8850: 
                   8851: sub fetch_enrollment_query {
1.511     raeburn  8852:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8853:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8854:     my $maxtries = 1;
1.508     raeburn  8855:     if ($context eq 'automated') {
                   8856:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8857:         $sleep = 2;
                   8858:         $loopmax = 100;
1.547     raeburn  8859:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8860:     } else {
                   8861:         $homeserver = &homeserver($cnum,$dom);
                   8862:     }
1.838     albertel 8863:     my $host=&hostname($homeserver);
1.506     raeburn  8864:     my $cmd = '';
1.1000    raeburn  8865:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8866:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8867:     }
                   8868:     $cmd =~ s/%%$//;
                   8869:     $cmd = &escape($cmd);
                   8870:     my $query = 'fetchenrollment';
1.620     albertel 8871:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8872:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8873:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8874:         return 'error: '.$queryid;
                   8875:     }
1.1172.2.93  raeburn  8876:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8877:     my $tries = 1;
                   8878:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8879:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8880:         $tries ++;
                   8881:     }
1.526     raeburn  8882:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8883:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8884:     } else {
1.901     albertel 8885:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8886:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8887:             foreach my $line (@responses) {
                   8888:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8889:                 $$replyref{$key} = $value;
                   8890:             }
                   8891:         } else {
1.1117    foxr     8892:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8893:             foreach my $line (@responses) {
                   8894:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8895:                 $$replyref{$key} = $value;
                   8896:                 if ($value > 0) {
1.800     albertel 8897:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8898:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8899:                         my $destname = $pathname.'/'.$filename;
                   8900:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8901:                         if ($xml_classlist =~ /^error/) {
                   8902:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8903:                         } else {
1.1172.2.96  raeburn  8904:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8905:                                 print FILE &unescape($xml_classlist);
                   8906:                                 close(FILE);
1.526     raeburn  8907:                             } else {
                   8908:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8909:                             }
                   8910:                         }
                   8911:                     }
                   8912:                 }
                   8913:             }
                   8914:         }
                   8915:         return 'ok';
                   8916:     }
                   8917:     return 'error';
                   8918: }
                   8919: 
1.242     www      8920: sub get_query_reply {
1.1172.2.79  raeburn  8921:     my ($queryid,$sleep,$loopmax) = @_;
                   8922:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8923:         $sleep = 0.2;
                   8924:     }
                   8925:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8926:         $loopmax = 100;
                   8927:     }
1.1117    foxr     8928:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8929:     my $reply='';
1.1172.2.79  raeburn  8930:     for (1..$loopmax) {
                   8931: 	sleep($sleep);
1.240     www      8932:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8933: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8934: 		$reply = join('',<$fh>);
                   8935: 		close($fh);
1.240     www      8936: 	   } else { return 'error: reply_file_error'; }
1.242     www      8937:            return &unescape($reply);
                   8938: 	}
1.240     www      8939:     }
1.242     www      8940:     return 'timeout:'.$queryid;
1.240     www      8941: }
                   8942: 
                   8943: sub courselog_query {
1.241     www      8944: #
                   8945: # possible filters:
                   8946: # url: url or symb
                   8947: # username
                   8948: # domain
                   8949: # action: view, submit, grade
                   8950: # start: timestamp
                   8951: # end: timestamp
                   8952: #
1.240     www      8953:     my (%filters)=@_;
1.620     albertel 8954:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8955:     if ($filters{'url'}) {
                   8956: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8957:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8958:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8959:     }
1.620     albertel 8960:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8961:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8962:     return &log_query($cname,$cdom,'courselog',%filters);
                   8963: }
                   8964: 
                   8965: sub userlog_query {
1.858     raeburn  8966: #
                   8967: # possible filters:
                   8968: # action: log check role
                   8969: # start: timestamp
                   8970: # end: timestamp
                   8971: #
1.240     www      8972:     my ($uname,$udom,%filters)=@_;
                   8973:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8974: }
                   8975: 
1.506     raeburn  8976: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8977: 
                   8978: sub auto_run {
1.508     raeburn  8979:     my ($cnum,$cdom) = @_;
1.876     raeburn  8980:     my $response = 0;
                   8981:     my $settings;
                   8982:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8983:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8984:         $settings = $domconfig{'autoenroll'};
                   8985:         if ($settings->{'run'} eq '1') {
                   8986:             $response = 1;
                   8987:         }
                   8988:     } else {
1.934     raeburn  8989:         my $homeserver;
                   8990:         if (&is_course($cdom,$cnum)) {
                   8991:             $homeserver = &homeserver($cnum,$cdom);
                   8992:         } else {
                   8993:             $homeserver = &domain($cdom,'primary');
                   8994:         }
                   8995:         if ($homeserver ne 'no_host') {
                   8996:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8997:         }
1.876     raeburn  8998:     }
1.506     raeburn  8999:     return $response;
                   9000: }
1.776     albertel 9001: 
1.506     raeburn  9002: sub auto_get_sections {
1.508     raeburn  9003:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9004:     my $homeserver;
                   9005:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9006:         $homeserver = &homeserver($cnum,$cdom);
                   9007:     }
                   9008:     if (!defined($homeserver)) { 
                   9009:         if ($cdom =~ /^$match_domain$/) {
                   9010:             $homeserver = &domain($cdom,'primary');
                   9011:         }
                   9012:     }
                   9013:     my @secs;
                   9014:     if (defined($homeserver)) {
                   9015:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9016:         unless ($response eq 'refused') {
                   9017:             @secs = split(/:/,$response);
                   9018:         }
1.506     raeburn  9019:     }
                   9020:     return @secs;
                   9021: }
1.776     albertel 9022: 
1.506     raeburn  9023: sub auto_new_course {
1.1099    raeburn  9024:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9025:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9026:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9027:     return $response;
                   9028: }
1.776     albertel 9029: 
1.506     raeburn  9030: sub auto_validate_courseID {
1.508     raeburn  9031:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9032:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9033:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9034:     return $response;
                   9035: }
1.776     albertel 9036: 
1.1007    raeburn  9037: sub auto_validate_instcode {
1.1020    raeburn  9038:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9039:     my ($homeserver,$response);
                   9040:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9041:         $homeserver = &homeserver($cnum,$cdom);
                   9042:     }
                   9043:     if (!defined($homeserver)) {
                   9044:         if ($cdom =~ /^$match_domain$/) {
                   9045:             $homeserver = &domain($cdom,'primary');
                   9046:         }
                   9047:     }
1.1065    raeburn  9048:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9049:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9050:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9051:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9052: }
                   9053: 
1.506     raeburn  9054: sub auto_create_password {
1.873     raeburn  9055:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9056:     my ($homeserver,$response);
1.506     raeburn  9057:     my $create_passwd = 0;
                   9058:     my $authchk = '';
1.873     raeburn  9059:     if ($udom =~ /^$match_domain$/) {
                   9060:         $homeserver = &domain($udom,'primary');
                   9061:     }
                   9062:     if ($homeserver eq '') {
                   9063:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9064:             $homeserver = &homeserver($cnum,$cdom);
                   9065:         }
                   9066:     }
                   9067:     if ($homeserver eq '') {
                   9068:         $authchk = 'nodomain';
1.506     raeburn  9069:     } else {
1.873     raeburn  9070:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9071:         if ($response eq 'refused') {
                   9072:             $authchk = 'refused';
                   9073:         } else {
1.901     albertel 9074:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9075:         }
1.506     raeburn  9076:     }
                   9077:     return ($authparam,$create_passwd,$authchk);
                   9078: }
                   9079: 
1.706     raeburn  9080: sub auto_photo_permission {
                   9081:     my ($cnum,$cdom,$students) = @_;
                   9082:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9083:     my ($outcome,$perm_reqd,$conditions) = 
                   9084: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9085:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9086: 	return (undef,undef);
                   9087:     }
1.706     raeburn  9088:     return ($outcome,$perm_reqd,$conditions);
                   9089: }
                   9090: 
                   9091: sub auto_checkphotos {
                   9092:     my ($uname,$udom,$pid) = @_;
                   9093:     my $homeserver = &homeserver($uname,$udom);
                   9094:     my ($result,$resulttype);
                   9095:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9096: 				   &escape($uname).':'.&escape($pid),
                   9097: 				   $homeserver));
1.709     albertel 9098:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9099: 	return (undef,undef);
                   9100:     }
1.706     raeburn  9101:     if ($outcome) {
                   9102:         ($result,$resulttype) = split(/:/,$outcome);
                   9103:     } 
                   9104:     return ($result,$resulttype);
                   9105: }
                   9106: 
                   9107: sub auto_photochoice {
                   9108:     my ($cnum,$cdom) = @_;
                   9109:     my $homeserver = &homeserver($cnum,$cdom);
                   9110:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9111: 						       &escape($cdom),
                   9112: 						       $homeserver)));
1.709     albertel 9113:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9114: 	return (undef,undef);
                   9115:     }
1.706     raeburn  9116:     return ($update,$comment);
                   9117: }
                   9118: 
                   9119: sub auto_photoupdate {
                   9120:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9121:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9122:     my $host=&hostname($homeserver);
1.706     raeburn  9123:     my $cmd = '';
                   9124:     my $maxtries = 1;
1.800     albertel 9125:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9126:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9127:     }
                   9128:     $cmd =~ s/%%$//;
                   9129:     $cmd = &escape($cmd);
                   9130:     my $query = 'institutionalphotos';
                   9131:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9132:     unless ($queryid=~/^\Q$host\E\_/) {
                   9133:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9134:         return 'error: '.$queryid;
                   9135:     }
                   9136:     my $reply = &get_query_reply($queryid);
                   9137:     my $tries = 1;
                   9138:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9139:         $reply = &get_query_reply($queryid);
                   9140:         $tries ++;
                   9141:     }
                   9142:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9143:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9144:     } else {
                   9145:         my @responses = split(/:/,$reply);
                   9146:         my $outcome = shift(@responses); 
                   9147:         foreach my $item (@responses) {
                   9148:             my ($key,$value) = split(/=/,$item);
                   9149:             $$photo{$key} = $value;
                   9150:         }
                   9151:         return $outcome;
                   9152:     }
                   9153:     return 'error';
                   9154: }
                   9155: 
1.521     raeburn  9156: sub auto_instcode_format {
1.793     albertel 9157:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9158: 	$cat_order) = @_;
1.521     raeburn  9159:     my $courses = '';
1.772     raeburn  9160:     my @homeservers;
1.521     raeburn  9161:     if ($caller eq 'global') {
1.841     albertel 9162: 	my %servers = &get_servers($codedom,'library');
                   9163: 	foreach my $tryserver (keys(%servers)) {
                   9164: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9165: 		push(@homeservers,$tryserver);
                   9166: 	    }
1.584     raeburn  9167:         }
1.1022    raeburn  9168:     } elsif ($caller eq 'requests') {
                   9169:         if ($codedom =~ /^$match_domain$/) {
                   9170:             my $chome = &domain($codedom,'primary');
                   9171:             unless ($chome eq 'no_host') {
                   9172:                 push(@homeservers,$chome);
                   9173:             }
                   9174:         }
1.521     raeburn  9175:     } else {
1.772     raeburn  9176:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9177:     }
1.793     albertel 9178:     foreach my $code (keys(%{$instcodes})) {
                   9179:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9180:     }
                   9181:     chop($courses);
1.772     raeburn  9182:     my $ok_response = 0;
                   9183:     my $response;
                   9184:     while (@homeservers > 0 && $ok_response == 0) {
                   9185:         my $server = shift(@homeservers); 
                   9186:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9187:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9188:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9189: 		split(/:/,$response);
1.772     raeburn  9190:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9191:             push(@{$codetitles},&str2array($codetitles_str));
                   9192:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9193:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9194:             $ok_response = 1;
                   9195:         }
                   9196:     }
                   9197:     if ($ok_response) {
1.521     raeburn  9198:         return 'ok';
1.772     raeburn  9199:     } else {
                   9200:         return $response;
1.521     raeburn  9201:     }
                   9202: }
                   9203: 
1.792     raeburn  9204: sub auto_instcode_defaults {
                   9205:     my ($domain,$returnhash,$code_order) = @_;
                   9206:     my @homeservers;
1.841     albertel 9207: 
                   9208:     my %servers = &get_servers($domain,'library');
                   9209:     foreach my $tryserver (keys(%servers)) {
                   9210: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9211: 	    push(@homeservers,$tryserver);
                   9212: 	}
1.792     raeburn  9213:     }
1.841     albertel 9214: 
1.792     raeburn  9215:     my $response;
1.841     albertel 9216:     foreach my $server (@homeservers) {
1.792     raeburn  9217:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9218:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9219: 	
                   9220: 	foreach my $pair (split(/\&/,$response)) {
                   9221: 	    my ($name,$value)=split(/\=/,$pair);
                   9222: 	    if ($name eq 'code_order') {
                   9223: 		@{$code_order} = split(/\&/,&unescape($value));
                   9224: 	    } else {
                   9225: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9226: 	    }
                   9227: 	}
                   9228: 	return 'ok';
1.792     raeburn  9229:     }
1.841     albertel 9230: 
                   9231:     return $response;
1.1003    raeburn  9232: }
                   9233: 
                   9234: sub auto_possible_instcodes {
1.1007    raeburn  9235:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9236:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9237:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9238:         return;
                   9239:     }
1.1003    raeburn  9240:     my (@homeservers,$uhome);
                   9241:     if (defined(&domain($domain,'primary'))) {
                   9242:         $uhome=&domain($domain,'primary');
                   9243:         push(@homeservers,&domain($domain,'primary'));
                   9244:     } else {
                   9245:         my %servers = &get_servers($domain,'library');
                   9246:         foreach my $tryserver (keys(%servers)) {
                   9247:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9248:                 push(@homeservers,$tryserver);
                   9249:             }
                   9250:         }
                   9251:     }
                   9252:     my $response;
                   9253:     foreach my $server (@homeservers) {
                   9254:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9255:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9256:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9257:             split(':',$response);
                   9258:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9259:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9260:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9261:             my ($name,$value)=split('=',$item);
                   9262:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9263:         }
                   9264:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9265:             my ($name,$value)=split('=',$item);
                   9266:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9267:         }
                   9268:         return 'ok';
                   9269:     }
                   9270:     return $response;
                   9271: }
1.792     raeburn  9272: 
1.1010    raeburn  9273: sub auto_courserequest_checks {
                   9274:     my ($dom) = @_;
1.1020    raeburn  9275:     my ($homeserver,%validations);
                   9276:     if ($dom =~ /^$match_domain$/) {
                   9277:         $homeserver = &domain($dom,'primary');
                   9278:     }
                   9279:     unless ($homeserver eq 'no_host') {
                   9280:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9281:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9282:             my @items = split(/&/,$response);
                   9283:             foreach my $item (@items) {
                   9284:                 my ($key,$value) = split('=',$item);
                   9285:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9286:             }
                   9287:         }
                   9288:     }
1.1010    raeburn  9289:     return %validations; 
                   9290: }
                   9291: 
1.1020    raeburn  9292: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9293:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9294:     my ($homeserver,$response);
                   9295:     if ($dom =~ /^$match_domain$/) {
                   9296:         $homeserver = &domain($dom,'primary');
                   9297:     }
1.1172.2.43  raeburn  9298:     unless ($homeserver eq 'no_host') {
                   9299:         my $customdata;
                   9300:         if (ref($custominfo) eq 'HASH') {
                   9301:             $customdata = &freeze_escape($custominfo);
                   9302:         }
1.1020    raeburn  9303:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9304:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9305:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9306:                                     $customdata,$homeserver));
1.1020    raeburn  9307:     }
                   9308:     return $response;
                   9309: }
                   9310: 
1.777     albertel 9311: sub auto_validate_class_sec {
1.918     raeburn  9312:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9313:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9314:     my $ownerlist;
                   9315:     if (ref($owners) eq 'ARRAY') {
                   9316:         $ownerlist = join(',',@{$owners});
                   9317:     } else {
                   9318:         $ownerlist = $owners;
                   9319:     }
1.773     raeburn  9320:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9321:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9322:     return $response;
                   9323: }
                   9324: 
1.1172.2.94  raeburn  9325: sub auto_validate_instclasses {
                   9326:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9327:     my ($homeserver,%validations);
                   9328:     $homeserver = &homeserver($cnum,$cdom);
                   9329:     unless ($homeserver eq 'no_host') {
                   9330:         my $ownerlist;
                   9331:         if (ref($owners) eq 'ARRAY') {
                   9332:             $ownerlist = join(',',@{$owners});
                   9333:         } else {
                   9334:             $ownerlist = $owners;
                   9335:         }
                   9336:         if (ref($classesref) eq 'HASH') {
                   9337:             my $classes = &freeze_escape($classesref);
                   9338:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9339:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9340:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9341:                 my @items = split(/&/,$response);
                   9342:                 foreach my $item (@items) {
                   9343:                     my ($key,$value) = split('=',$item);
                   9344:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9345:                 }
                   9346:             }
                   9347:         }
                   9348:     }
                   9349:     return %validations;
                   9350: }
                   9351: 
1.1172.2.38  raeburn  9352: sub auto_crsreq_update {
                   9353:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9354:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9355:     my ($homeserver,%crsreqresponse);
                   9356:     if ($cdom =~ /^$match_domain$/) {
                   9357:         $homeserver = &domain($cdom,'primary');
                   9358:     }
                   9359:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9360:         my $info;
                   9361:         if (ref($inbound) eq 'HASH') {
                   9362:             $info = &freeze_escape($inbound);
                   9363:         }
                   9364:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9365:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9366:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9367:                             &escape($title).':'.&escape($code).':'.
                   9368:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9369:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9370:             my @items = split(/&/,$response);
                   9371:             foreach my $item (@items) {
                   9372:                 my ($key,$value) = split('=',$item);
                   9373:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9374:             }
                   9375:         }
                   9376:     }
                   9377:     return \%crsreqresponse;
                   9378: }
                   9379: 
1.1172.2.78  raeburn  9380: sub auto_export_grades {
                   9381:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9382:     my ($homeserver,%exportresponse);
                   9383:     if ($cdom =~ /^$match_domain$/) {
                   9384:         $homeserver = &domain($cdom,'primary');
                   9385:     }
                   9386:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9387:         my $info;
                   9388:         if (ref($inforef) eq 'HASH') {
                   9389:             $info = &freeze_escape($inforef);
                   9390:         }
                   9391:         if (ref($gradesref) eq 'HASH') {
                   9392:             my $grades = &freeze_escape($gradesref);
                   9393:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9394:                                 $info.':'.$grades,$homeserver);
                   9395:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9396:                 my @items = split(/&/,$response);
                   9397:                 foreach my $item (@items) {
                   9398:                     my ($key,$value) = split('=',$item);
                   9399:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9400:                 }
                   9401:             }
                   9402:         }
                   9403:     }
                   9404:     return \%exportresponse;
                   9405: }
                   9406: 
1.1172.2.68  raeburn  9407: sub check_instcode_cloning {
                   9408:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9409:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9410:         return;
                   9411:     }
                   9412:     my $canclone;
                   9413:     if (@{$code_order} > 0) {
                   9414:         my $instcoderegexp ='^';
                   9415:         my @clonecodes = split(/\&/,$cloner);
                   9416:         foreach my $item (@{$code_order}) {
                   9417:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9418:                 foreach my $pair (@clonecodes) {
                   9419:                     my ($key,$val) = split(/\=/,$pair,2);
                   9420:                     $val = &unescape($val);
                   9421:                     if ($key eq $item) {
                   9422:                         $instcoderegexp .= '('.$val.')';
                   9423:                         last;
                   9424:                     }
                   9425:                 }
                   9426:             } else {
                   9427:                 $instcoderegexp .= $codedefaults->{$item};
                   9428:             }
                   9429:         }
                   9430:         $instcoderegexp .= '$';
                   9431:         my (@from,@to);
                   9432:         eval {
                   9433:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9434:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9435:         };
                   9436:         if ((@from > 0) && (@to > 0)) {
                   9437:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9438:             if (!@diffs) {
                   9439:                 $canclone = 1;
                   9440:             }
                   9441:         }
                   9442:     }
                   9443:     return $canclone;
                   9444: }
                   9445: 
                   9446: sub default_instcode_cloning {
                   9447:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9448:     my (%codedefaults,@code_order,$canclone);
                   9449:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9450:         %codedefaults = %{$codedefaultsref};
                   9451:         @code_order = @{$codeorderref};
                   9452:     } elsif ($clonedom) {
                   9453:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9454:     }
                   9455:     if (($domdefclone) && (@code_order)) {
                   9456:         my @clonecodes = split(/\+/,$domdefclone);
                   9457:         my $instcoderegexp ='^';
                   9458:         foreach my $item (@code_order) {
                   9459:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9460:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9461:             } else {
                   9462:                 $instcoderegexp .= $codedefaults{$item};
                   9463:             }
                   9464:         }
                   9465:         $instcoderegexp .= '$';
                   9466:         my (@from,@to);
                   9467:         eval {
                   9468:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9469:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9470:         };
                   9471:         if ((@from > 0) && (@to > 0)) {
                   9472:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9473:             if (!@diffs) {
                   9474:                 $canclone = 1;
                   9475:             }
                   9476:         }
                   9477:     }
                   9478:     return $canclone;
                   9479: }
                   9480: 
1.679     raeburn  9481: # ------------------------------------------------------- Course Group routines
                   9482: 
                   9483: sub get_coursegroups {
1.809     raeburn  9484:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9485:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9486: }
                   9487: 
1.679     raeburn  9488: sub modify_coursegroup {
                   9489:     my ($cdom,$cnum,$groupsettings) = @_;
                   9490:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9491: }
                   9492: 
1.809     raeburn  9493: sub toggle_coursegroup_status {
                   9494:     my ($cdom,$cnum,$group,$action) = @_;
                   9495:     my ($from_namespace,$to_namespace);
                   9496:     if ($action eq 'delete') {
                   9497:         $from_namespace = 'coursegroups';
                   9498:         $to_namespace = 'deleted_groups';
                   9499:     } else {
                   9500:         $from_namespace = 'deleted_groups';
                   9501:         $to_namespace = 'coursegroups';
                   9502:     }
                   9503:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9504:     if (my $tmp = &error(%curr_group)) {
                   9505:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9506:         return ('read error',$tmp);
                   9507:     } else {
                   9508:         my %savedsettings = %curr_group; 
1.809     raeburn  9509:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9510:         my $deloutcome;
                   9511:         if ($result eq 'ok') {
1.809     raeburn  9512:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9513:         } else {
                   9514:             return ('write error',$result);
                   9515:         }
                   9516:         if ($deloutcome eq 'ok') {
                   9517:             return 'ok';
                   9518:         } else {
                   9519:             return ('delete error',$deloutcome);
                   9520:         }
                   9521:     }
                   9522: }
                   9523: 
1.679     raeburn  9524: sub modify_group_roles {
1.957     raeburn  9525:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9526:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9527:     my $role = 'gr/'.&escape($userprivs);
                   9528:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9529:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9530:     if ($result eq 'ok') {
                   9531:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9532:     }
1.679     raeburn  9533:     return $result;
                   9534: }
                   9535: 
                   9536: sub modify_coursegroup_membership {
                   9537:     my ($cdom,$cnum,$membership) = @_;
                   9538:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9539:     return $result;
                   9540: }
                   9541: 
1.682     raeburn  9542: sub get_active_groups {
                   9543:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9544:     my $now = time;
                   9545:     my %groups = ();
                   9546:     foreach my $key (keys(%env)) {
1.811     albertel 9547:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9548:             my ($start,$end) = split(/\./,$env{$key});
                   9549:             if (($end!=0) && ($end<$now)) { next; }
                   9550:             if (($start!=0) && ($start>$now)) { next; }
                   9551:             if ($1 eq $cdom && $2 eq $cnum) {
                   9552:                 $groups{$3} = $env{$key} ;
                   9553:             }
                   9554:         }
                   9555:     }
                   9556:     return %groups;
                   9557: }
                   9558: 
1.683     raeburn  9559: sub get_group_membership {
                   9560:     my ($cdom,$cnum,$group) = @_;
                   9561:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9562: }
                   9563: 
                   9564: sub get_users_groups {
                   9565:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9566:     my @usersgroups;
1.683     raeburn  9567:     my $cachetime=1800;
                   9568: 
                   9569:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9570:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9571:     if (defined($cached)) {
1.734     albertel 9572:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9573:     } else {  
                   9574:         $grouplist = '';
1.816     raeburn  9575:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9576:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9577:         my $access_end = $env{'course.'.$courseid.
                   9578:                               '.default_enrollment_end_date'};
                   9579:         my $now = time;
                   9580:         foreach my $key (keys(%roleshash)) {
                   9581:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9582:                 my $group = $1;
                   9583:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9584:                     my $start = $2;
                   9585:                     my $end = $1;
                   9586:                     if ($start == -1) { next; } # deleted from group
                   9587:                     if (($start!=0) && ($start>$now)) { next; }
                   9588:                     if (($end!=0) && ($end<$now)) {
                   9589:                         if ($access_end && $access_end < $now) {
                   9590:                             if ($access_end - $end < 86400) {
                   9591:                                 push(@usersgroups,$group);
1.733     raeburn  9592:                             }
                   9593:                         }
1.817     raeburn  9594:                         next;
1.733     raeburn  9595:                     }
1.817     raeburn  9596:                     push(@usersgroups,$group);
1.683     raeburn  9597:                 }
                   9598:             }
                   9599:         }
1.817     raeburn  9600:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9601:         $grouplist = join(':',@usersgroups);
                   9602:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9603:     }
1.733     raeburn  9604:     return @usersgroups;
1.683     raeburn  9605: }
                   9606: 
                   9607: sub devalidate_getgroups_cache {
                   9608:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9609:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9610: 
1.683     raeburn  9611:     my $hashid="$udom:$uname:$courseid";
                   9612:     &devalidate_cache_new('getgroups',$hashid);
                   9613: }
                   9614: 
1.12      www      9615: # ------------------------------------------------------------------ Plain Text
                   9616: 
                   9617: sub plaintext {
1.988     raeburn  9618:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9619:     if ($short =~ m{^cr/}) {
1.758     albertel 9620: 	return (split('/',$short))[-1];
                   9621:     }
1.742     raeburn  9622:     if (!defined($cid)) {
                   9623:         $cid = $env{'request.course.id'};
                   9624:     }
                   9625:     my %rolenames = (
1.1008    raeburn  9626:                       Course    => 'std',
                   9627:                       Community => 'alt1',
1.742     raeburn  9628:                     );
1.1037    raeburn  9629:     if ($cid ne '') {
                   9630:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9631:             unless ($forcedefault) {
                   9632:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9633:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9634:                 return &Apache::lonlocal::mt($roletext);
                   9635:             }
                   9636:         }
                   9637:     }
                   9638:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9639:         (defined($rolenames{$type})) && 
                   9640:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9641:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9642:     } elsif ($cid ne '') {
                   9643:         my $crstype = $env{'course.'.$cid.'.type'};
                   9644:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9645:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9646:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9647:         }
1.742     raeburn  9648:     }
1.1037    raeburn  9649:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9650: }
                   9651: 
                   9652: # ----------------------------------------------------------------- Assign Role
                   9653: 
                   9654: sub assignrole {
1.957     raeburn  9655:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9656:         $context)=@_;
1.21      www      9657:     my $mrole;
                   9658:     if ($role =~ /^cr\//) {
1.393     www      9659:         my $cwosec=$url;
1.811     albertel 9660:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9661: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9662:            my $refused = 1;
                   9663:            if ($context eq 'requestcourses') {
                   9664:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9665:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9666:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9667:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9668:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9669:                            if ($crsenv{'internal.courseowner'} eq
                   9670:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9671:                                $refused = '';
                   9672:                            }
                   9673:                        }
                   9674:                    }
                   9675:                }
                   9676:            }
                   9677:            if ($refused) {
                   9678:                &logthis('Refused custom assignrole: '.
                   9679:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9680:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9681:                return 'refused';
                   9682:            }
1.104     www      9683:         }
1.21      www      9684:         $mrole='cr';
1.678     raeburn  9685:     } elsif ($role =~ /^gr\//) {
                   9686:         my $cwogrp=$url;
1.811     albertel 9687:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9688:         unless (&allowed('mdg',$cwogrp)) {
                   9689:             &logthis('Refused group assignrole: '.
                   9690:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9691:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9692:             return 'refused';
                   9693:         }
                   9694:         $mrole='gr';
1.21      www      9695:     } else {
1.82      www      9696:         my $cwosec=$url;
1.811     albertel 9697:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9698:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9699:             my $refused;
                   9700:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9701:                 if (!(&allowed('c'.$role,$url))) {
                   9702:                     $refused = 1;
                   9703:                 }
                   9704:             } else {
                   9705:                 $refused = 1;
                   9706:             }
1.947     raeburn  9707:             if ($refused) {
1.1045    raeburn  9708:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9709:                 if (!$selfenroll && $context eq 'course') {
                   9710:                     my %crsenv;
                   9711:                     if ($role eq 'cc' || $role eq 'co') {
                   9712:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9713:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9714:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9715:                                 if ($crsenv{'internal.courseowner'} eq 
                   9716:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9717:                                     $refused = '';
                   9718:                                 }
                   9719:                             }
                   9720:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9721:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9722:                                 if ($crsenv{'internal.courseowner'} eq 
                   9723:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9724:                                     $refused = '';
                   9725:                                 }
                   9726:                             }
                   9727:                         }
                   9728:                     }
                   9729:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9730:                     $refused = '';
1.1017    raeburn  9731:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9732:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9733:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9734:                         my $wrongcc;
                   9735:                         if ($cnum =~ /^$match_community$/) {
                   9736:                             $wrongcc = 1 if ($role eq 'cc');
                   9737:                         } else {
                   9738:                             $wrongcc = 1 if ($role eq 'co');
                   9739:                         }
                   9740:                         unless ($wrongcc) {
                   9741:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9742:                             if ($crsenv{'internal.courseowner'} eq 
                   9743:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9744:                                 $refused = '';
                   9745:                             }
1.1017    raeburn  9746:                         }
                   9747:                     }
1.1172.2.9  raeburn  9748:                 } elsif ($context eq 'requestauthor') {
                   9749:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9750:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9751:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9752:                             $refused = '';
                   9753:                         } else {
                   9754:                             my %domdefaults = &get_domain_defaults($udom);
                   9755:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9756:                                 my $checkbystatus;
                   9757:                                 if ($env{'user.adv'}) {
                   9758:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9759:                                     if ($disposition eq 'automatic') {
                   9760:                                         $refused = '';
                   9761:                                     } elsif ($disposition eq '') {
                   9762:                                         $checkbystatus = 1;
                   9763:                                     }
                   9764:                                 } else {
                   9765:                                     $checkbystatus = 1;
                   9766:                                 }
                   9767:                                 if ($checkbystatus) {
                   9768:                                     if ($env{'environment.inststatus'}) {
                   9769:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9770:                                         foreach my $type (@inststatuses) {
                   9771:                                             if (($type ne '') &&
                   9772:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9773:                                                 $refused = '';
                   9774:                                             }
                   9775:                                         }
                   9776:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9777:                                         $refused = '';
                   9778:                                     }
                   9779:                                 }
                   9780:                             }
                   9781:                         }
                   9782:                     }
1.1017    raeburn  9783:                 }
                   9784:                 if ($refused) {
1.947     raeburn  9785:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9786:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9787: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9788:                     return 'refused';
                   9789:                 }
1.932     raeburn  9790:             }
1.1131    raeburn  9791:         } elsif ($role eq 'au') {
                   9792:             if ($url ne '/'.$udom.'/') {
                   9793:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9794:                          ' to assign author role for '.$uname.':'.$udom.
                   9795:                          ' in domain: '.$url.' refused (wrong domain).');
                   9796:                 return 'refused';
                   9797:             }
1.104     www      9798:         }
1.21      www      9799:         $mrole=$role;
                   9800:     }
1.620     albertel 9801:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9802:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9803:     if ($end) { $command.='_'.$end; }
1.21      www      9804:     if ($start) {
                   9805: 	if ($end) { 
1.81      www      9806:            $command.='_'.$start; 
1.21      www      9807:         } else {
1.81      www      9808:            $command.='_0_'.$start;
1.21      www      9809:         }
                   9810:     }
1.739     raeburn  9811:     my $origstart = $start;
                   9812:     my $origend = $end;
1.957     raeburn  9813:     my $delflag;
1.357     www      9814: # actually delete
                   9815:     if ($deleteflag) {
1.373     www      9816: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9817: # modify command to delete the role
1.620     albertel 9818:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9819:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9820: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9821: # set start and finish to negative values for userrolelog
                   9822:            $start=-1;
                   9823:            $end=-1;
1.957     raeburn  9824:            $delflag = 1;
1.357     www      9825:         }
                   9826:     }
                   9827: # send command
1.349     www      9828:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9829: # log new user role if status is ok
1.349     www      9830:     if ($answer eq 'ok') {
1.663     raeburn  9831: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9832:         if (($role eq 'cc') || ($role eq 'in') ||
                   9833:             ($role eq 'ep') || ($role eq 'ad') ||
                   9834:             ($role eq 'ta') || ($role eq 'st') ||
                   9835:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9836:             ($role eq 'co')) {
1.1172.2.13  raeburn  9837: # for course roles, perform group memberships changes triggered by role change.
                   9838:             unless ($role =~ /^gr/) {
                   9839:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9840:                                                  $origstart,$selfenroll,$context);
                   9841:             }
1.1172.2.9  raeburn  9842:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9843:                            $selfenroll,$context);
                   9844:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9845:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9846:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9847:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9848:                            $context);
                   9849:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9850:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9851:                              $context);
                   9852:         }
1.1053    raeburn  9853:         if ($role eq 'cc') {
                   9854:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9855:         }
1.349     www      9856:     }
                   9857:     return $answer;
1.169     harris41 9858: }
                   9859: 
1.1053    raeburn  9860: sub autoupdate_coowners {
                   9861:     my ($url,$end,$start,$uname,$udom) = @_;
                   9862:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9863:     if (($cdom ne '') && ($cnum ne '')) {
                   9864:         my $now = time;
                   9865:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9866:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9867:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9868:             my $instcode = $coursehash{'internal.coursecode'};
                   9869:             if ($instcode ne '') {
1.1056    raeburn  9870:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9871:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9872:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9873:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9874:                         if ($result eq 'valid') {
                   9875:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9876:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9877:                                     push(@newcoowners,$coowner);
                   9878:                                 }
                   9879:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9880:                                     push(@newcoowners,$uname.':'.$udom);
                   9881:                                 }
                   9882:                                 @newcoowners = sort(@newcoowners);
                   9883:                             } else {
                   9884:                                 push(@newcoowners,$uname.':'.$udom);
                   9885:                             }
                   9886:                         } else {
                   9887:                             if ($coursehash{'internal.co-owners'}) {
                   9888:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9889:                                     unless ($coowner eq $uname.':'.$udom) {
                   9890:                                         push(@newcoowners,$coowner);
                   9891:                                     }
                   9892:                                 }
                   9893:                                 unless (@newcoowners > 0) {
                   9894:                                     $delcoowners = 1;
                   9895:                                     $coowners = '';
                   9896:                                 }
                   9897:                             }
                   9898:                         }
                   9899:                         if (@newcoowners || $delcoowners) {
                   9900:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9901:                                             $delcoowners,@newcoowners);
                   9902:                         }
                   9903:                     }
                   9904:                 }
                   9905:             }
                   9906:         }
                   9907:     }
                   9908: }
                   9909: 
                   9910: sub store_coowners {
                   9911:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9912:     my $cid = $cdom.'_'.$cnum;
                   9913:     my ($coowners,$delresult,$putresult);
                   9914:     if (@newcoowners) {
                   9915:         $coowners = join(',',@newcoowners);
                   9916:         my %coownershash = (
                   9917:                             'internal.co-owners' => $coowners,
                   9918:                            );
                   9919:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9920:         if ($putresult eq 'ok') {
                   9921:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9922:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9923:             }
                   9924:         }
                   9925:     }
                   9926:     if ($delcoowners) {
                   9927:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9928:         if ($delresult eq 'ok') {
                   9929:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9930:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9931:             }
                   9932:         }
                   9933:     }
                   9934:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9935:         my %crsinfo =
                   9936:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9937:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9938:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9939:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9940:         }
                   9941:     }
                   9942: }
                   9943: 
1.169     harris41 9944: # -------------------------------------------------- Modify user authentication
1.197     www      9945: # Overrides without validation
                   9946: 
1.169     harris41 9947: sub modifyuserauth {
                   9948:     my ($udom,$uname,$umode,$upass)=@_;
                   9949:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9950:     my $allowed;
                   9951:     if (&allowed('mau',$udom)) {
                   9952:         $allowed = 1;
                   9953:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9954:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9955:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9956:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9957:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9958:         if (($cdom ne '') && ($cnum ne '')) {
                   9959:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9960:             if ($is_owner) {
                   9961:                 $allowed = 1;
                   9962:             }
                   9963:         }
                   9964:     }
                   9965:     unless ($allowed) { return 'refused'; }
1.197     www      9966:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9967:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9968:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9969:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9970: 		     &escape($upass),$uhome);
1.620     albertel 9971:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9972:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9973:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9974:     &log($udom,,$uname,$uhome,
1.620     albertel 9975:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9976:                                      $env{'user.name'}.', '.$umode.
1.197     www      9977:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9978:     unless ($reply eq 'ok') {
1.197     www      9979:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9980: 	return 'error: '.$reply;
                   9981:     }   
1.170     harris41 9982:     return 'ok';
1.80      www      9983: }
                   9984: 
1.81      www      9985: # --------------------------------------------------------------- Modify a user
1.80      www      9986: 
1.81      www      9987: sub modifyuser {
1.206     matthew  9988:     my ($udom,    $uname, $uid,
                   9989:         $umode,   $upass, $first,
                   9990:         $middle,  $last,  $gene,
1.1058    raeburn  9991:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9992:     $udom= &LONCAPA::clean_domain($udom);
                   9993:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9994:     my $showcandelete = 'none';
                   9995:     if (ref($candelete) eq 'ARRAY') {
                   9996:         if (@{$candelete} > 0) {
                   9997:             $showcandelete = join(', ',@{$candelete});
                   9998:         }
                   9999:     }
1.81      www      10000:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10001:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10002: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10003:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10004:                                      ' desiredhome not specified'). 
1.620     albertel 10005:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10006:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10007:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10008:     my $newuser;
                   10009:     if ($uhome eq 'no_host') {
                   10010:         $newuser = 1;
                   10011:     }
1.80      www      10012: # ----------------------------------------------------------------- Create User
1.406     albertel 10013:     if (($uhome eq 'no_host') && 
                   10014: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10015:         my $unhome='';
1.844     albertel 10016:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10017:             $unhome = $desiredhome;
1.620     albertel 10018: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10019: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10020:         } else { # load balancing routine for determining $unhome
1.81      www      10021:             my $loadm=10000000;
1.841     albertel 10022: 	    my %servers = &get_servers($udom,'library');
                   10023: 	    foreach my $tryserver (keys(%servers)) {
                   10024: 		my $answer=reply('load',$tryserver);
                   10025: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10026: 		    $loadm=$answer;
                   10027: 		    $unhome=$tryserver;
                   10028: 		}
1.80      www      10029: 	    }
                   10030:         }
                   10031:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10032: 	    return 'error: unable to find a home server for '.$uname.
                   10033:                    ' in domain '.$udom;
1.80      www      10034:         }
                   10035:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10036:                          &escape($upass),$unhome);
                   10037: 	unless ($reply eq 'ok') {
                   10038:             return 'error: '.$reply;
                   10039:         }   
1.230     stredwic 10040:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10041:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10042: 	    return 'error: unable verify users home machine.';
1.80      www      10043:         }
1.209     matthew  10044:     }   # End of creation of new user
1.80      www      10045: # ---------------------------------------------------------------------- Add ID
                   10046:     if ($uid) {
                   10047:        $uid=~tr/A-Z/a-z/;
                   10048:        my %uidhash=&idrget($udom,$uname);
1.196     www      10049:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10050:          && (!$forceid)) {
1.80      www      10051: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10052: 	      return 'error: user id "'.$uid.'" does not match '.
                   10053:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10054:           }
                   10055:        } else {
                   10056: 	  &idput($udom,($uname => $uid));
                   10057:        }
                   10058:     }
                   10059: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10060:     my @tmp=&get('environment',
1.899     raeburn  10061: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10062:                     'permanentemail','inststatus'],
1.134     albertel 10063: 		   $udom,$uname);
1.1075    raeburn  10064:     my (%names,%oldnames);
1.313     matthew  10065:     if ($tmp[0] =~ m/^error:.*/) { 
                   10066:         %names=(); 
                   10067:     } else {
                   10068:         %names = @tmp;
1.1075    raeburn  10069:         %oldnames = %names;
1.313     matthew  10070:     }
1.388     www      10071: #
1.1058    raeburn  10072: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10073: # of users did not contain them), do not overwrite existing values
                   10074: # unless field is in $candelete array ref.  
                   10075: #
                   10076: 
                   10077:     my @fields = ('firstname','middlename','lastname','generation',
                   10078:                   'permanentemail','id');
                   10079:     my %newvalues;
                   10080:     if (ref($candelete) eq 'ARRAY') {
                   10081:         foreach my $field (@fields) {
                   10082:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10083:                 if ($field eq 'firstname') {
                   10084:                     $names{$field} = $first;
                   10085:                 } elsif ($field eq 'middlename') {
                   10086:                     $names{$field} = $middle;
                   10087:                 } elsif ($field eq 'lastname') {
                   10088:                     $names{$field} = $last;
                   10089:                 } elsif ($field eq 'generation') { 
                   10090:                     $names{$field} = $gene;
                   10091:                 } elsif ($field eq 'permanentemail') {
                   10092:                     $names{$field} = $email;
                   10093:                 } elsif ($field eq 'id') {
                   10094:                     $names{$field}  = $uid;
                   10095:                 }
                   10096:             }
                   10097:         }
                   10098:     }
1.388     www      10099:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10100:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10101:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10102:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10103:     if ($email) {
                   10104:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10105:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10106:     }
1.899     raeburn  10107:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10108:     if (defined($inststatus)) {
                   10109:         $names{'inststatus'} = '';
                   10110:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10111:         if (ref($usertypes) eq 'HASH') {
                   10112:             my @okstatuses; 
                   10113:             foreach my $item (split(/:/,$inststatus)) {
                   10114:                 if (defined($usertypes->{$item})) {
                   10115:                     push(@okstatuses,$item);  
                   10116:                 }
                   10117:             }
                   10118:             if (@okstatuses) {
                   10119:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10120:             }
                   10121:         }
                   10122:     }
1.1075    raeburn  10123:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10124:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10125:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10126:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10127:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10128:     } else {
                   10129:         $logmsg .= ' during self creation';
                   10130:     }
1.1075    raeburn  10131:     my $changed;
                   10132:     if ($newuser) {
                   10133:         $changed = 1;
                   10134:     } else {
                   10135:         foreach my $field (@fields) {
                   10136:             if ($names{$field} ne $oldnames{$field}) {
                   10137:                 $changed = 1;
                   10138:                 last;
                   10139:             }
                   10140:         }
                   10141:     }
                   10142:     unless ($changed) {
                   10143:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10144:         &logthis($logmsg);
                   10145:         return 'ok';
                   10146:     }
                   10147:     my $reply = &put('environment', \%names, $udom,$uname);
                   10148:     if ($reply ne 'ok') { 
                   10149:         return 'error: '.$reply;
                   10150:     }
1.1087    raeburn  10151:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10152:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10153:     }
1.1075    raeburn  10154:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10155:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10156:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10157:     &logthis($logmsg);
1.134     albertel 10158:     return 'ok';
1.80      www      10159: }
                   10160: 
1.81      www      10161: # -------------------------------------------------------------- Modify student
1.80      www      10162: 
1.81      www      10163: sub modifystudent {
                   10164:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10165:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10166:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10167:     if (!$cid) {
1.620     albertel 10168: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10169: 	    return 'not_in_class';
                   10170: 	}
1.80      www      10171:     }
                   10172: # --------------------------------------------------------------- Make the user
1.81      www      10173:     my $reply=&modifyuser
1.209     matthew  10174: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10175:          $desiredhome,$email,$inststatus);
1.80      www      10176:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10177:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10178:     # student's environment
1.297     matthew  10179:     $uid = undef if (!$forceid);
1.455     albertel 10180:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10181: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10182:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10183:     return $reply;
                   10184: }
                   10185: 
                   10186: sub modify_student_enrollment {
1.1172.2.23  raeburn  10187:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10188:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10189:     my ($cdom,$cnum,$chome);
                   10190:     if (!$cid) {
1.620     albertel 10191: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10192: 	    return 'not_in_class';
                   10193: 	}
1.620     albertel 10194: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10195: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10196:     } else {
                   10197: 	($cdom,$cnum)=split(/_/,$cid);
                   10198:     }
1.620     albertel 10199:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10200:     if (!$chome) {
1.457     raeburn  10201: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10202:     }
1.455     albertel 10203:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10204:     # Make sure the user exists
1.81      www      10205:     my $uhome=&homeserver($uname,$udom);
                   10206:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10207: 	return 'error: no such user';
                   10208:     }
1.297     matthew  10209:     # Get student data if we were not given enough information
                   10210:     if (!defined($first)  || $first  eq '' || 
                   10211:         !defined($last)   || $last   eq '' || 
                   10212:         !defined($uid)    || $uid    eq '' || 
                   10213:         !defined($middle) || $middle eq '' || 
                   10214:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10215:         # They did not supply us with enough data to enroll the student, so
                   10216:         # we need to pick up more information.
1.297     matthew  10217:         my %tmp = &get('environment',
1.294     matthew  10218:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10219:                        ,$udom,$uname);
                   10220: 
1.800     albertel 10221:         #foreach my $key (keys(%tmp)) {
                   10222:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10223:         #}
1.294     matthew  10224:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10225:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10226:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10227:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10228:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10229:     }
1.556     albertel 10230:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10231:     my $user = "$uname:$udom";
                   10232:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10233:     my $reply=cput('classlist',
1.1148    raeburn  10234: 		   {$user => 
1.1172.2.76  raeburn  10235: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10236: 		   $cdom,$cnum);
1.1148    raeburn  10237:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10238:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10239:     } else { 
1.81      www      10240: 	return 'error: '.$reply;
                   10241:     }
1.297     matthew  10242:     # Add student role to user
1.83      www      10243:     my $uurl='/'.$cid;
1.81      www      10244:     $uurl=~s/\_/\//g;
                   10245:     if ($usec) {
                   10246: 	$uurl.='/'.$usec;
                   10247:     }
1.1148    raeburn  10248:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10249:                              $selfenroll,$context);
                   10250:     if ($result ne 'ok') {
                   10251:         if ($old_entry{$user} ne '') {
                   10252:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10253:         } else {
                   10254:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10255:         }
                   10256:     }
                   10257:     return $result; 
1.21      www      10258: }
                   10259: 
1.556     albertel 10260: sub format_name {
                   10261:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10262:     my $name;
                   10263:     if ($first ne 'lastname') {
                   10264: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10265:     } else {
                   10266: 	if ($lastname=~/\S/) {
                   10267: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10268: 	    $name=~s/\s+,/,/;
                   10269: 	} else {
                   10270: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10271: 	}
                   10272:     }
                   10273:     $name=~s/^\s+//;
                   10274:     $name=~s/\s+$//;
                   10275:     $name=~s/\s+/ /g;
                   10276:     return $name;
                   10277: }
                   10278: 
1.84      www      10279: # ------------------------------------------------- Write to course preferences
                   10280: 
                   10281: sub writecoursepref {
                   10282:     my ($courseid,%prefs)=@_;
                   10283:     $courseid=~s/^\///;
                   10284:     $courseid=~s/\_/\//g;
                   10285:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10286:     my $chome=homeserver($cnum,$cdomain);
                   10287:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10288: 	return 'error: no such course';
                   10289:     }
                   10290:     my $cstring='';
1.800     albertel 10291:     foreach my $pref (keys(%prefs)) {
                   10292: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10293:     }
1.84      www      10294:     $cstring=~s/\&$//;
                   10295:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10296: }
                   10297: 
                   10298: # ---------------------------------------------------------- Make/modify course
                   10299: 
                   10300: sub createcourse {
1.741     raeburn  10301:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10302:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10303:     $url=&declutter($url);
                   10304:     my $cid='';
1.1028    raeburn  10305:     if ($context eq 'requestcourses') {
                   10306:         my $can_create = 0;
                   10307:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10308:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10309:20):             my $reload;
                   10310:20):             if (($callercontext eq 'auto') &&
                   10311:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10312:20):                 $reload = 'reload';
                   10313:20):             }
                   10314:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10315:                                   $context)) {
                   10316:                 $can_create = 1;
                   10317:             }
                   10318:         } else {
                   10319:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10320:                                            $category);
                   10321:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10322:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10323:                 if (@curr > 0) {
                   10324:                     my @options = qw(approval validate autolimit);
                   10325:                     my $optregex = join('|',@options);
                   10326:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10327:                         $can_create = 1;
                   10328:                     }
                   10329:                 }
                   10330:             }
                   10331:         }
                   10332:         if ($can_create) {
                   10333:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10334:                 unless (&allowed('ccc',$udom)) {
                   10335:                     return 'refused'; 
                   10336:                 }
1.1017    raeburn  10337:             }
                   10338:         } else {
                   10339:             return 'refused';
                   10340:         }
1.1028    raeburn  10341:     } elsif (!&allowed('ccc',$udom)) {
                   10342:         return 'refused';
1.84      www      10343:     }
1.1011    raeburn  10344: # --------------------------------------------------------------- Get Unique ID
                   10345:     my $uname;
                   10346:     if ($cnum =~ /^$match_courseid$/) {
                   10347:         my $chome=&homeserver($cnum,$udom,'true');
                   10348:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10349:             $uname = $cnum;
                   10350:         } else {
1.1038    raeburn  10351:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10352:         }
                   10353:     } else {
1.1038    raeburn  10354:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10355:     }
                   10356:     return $uname if ($uname =~ /^error/);
                   10357: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10358:     if (!defined($course_server)) {
                   10359:         if (defined(&domain($udom,'primary'))) {
                   10360:             $course_server = &domain($udom,'primary');
                   10361:         } else {
                   10362:             $course_server = $env{'user.home'}; 
                   10363:         }
                   10364:     }
                   10365:     my %host_servers =
                   10366:         &Apache::lonnet::get_servers($udom,'library');
                   10367:     unless ($host_servers{$course_server}) {
                   10368:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10369:     }
1.84      www      10370: # ------------------------------------------------------------- Make the course
                   10371:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10372:                       $course_server);
1.84      www      10373:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10374:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10375:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10376: 	return 'error: no such course';
                   10377:     }
1.271     www      10378: # ----------------------------------------------------------------- Course made
1.516     raeburn  10379: # log existence
1.1029    raeburn  10380:     my $now = time;
1.918     raeburn  10381:     my $newcourse = {
                   10382:                     $udom.'_'.$uname => {
1.921     raeburn  10383:                                      description => $description,
                   10384:                                      inst_code   => $inst_code,
                   10385:                                      owner       => $course_owner,
                   10386:                                      type        => $crstype,
1.1029    raeburn  10387:                                      creator     => $env{'user.name'}.':'.
                   10388:                                                     $env{'user.domain'},
                   10389:                                      created     => $now,
                   10390:                                      context     => $context,
1.918     raeburn  10391:                                                 },
                   10392:                     };
1.921     raeburn  10393:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10394: # set toplevel url
1.271     www      10395:     my $topurl=$url;
                   10396:     unless ($nonstandard) {
                   10397: # ------------------------------------------ For standard courses, make top url
                   10398:         my $mapurl=&clutter($url);
1.278     www      10399:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10400:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10401: <map>
                   10402: <resource id="1" type="start"></resource>
                   10403: <resource id="2" src="$mapurl"></resource>
                   10404: <resource id="3" type="finish"></resource>
                   10405: <link index="1" from="1" to="2"></link>
                   10406: <link index="2" from="2" to="3"></link>
                   10407: </map>
                   10408: ENDINITMAP
                   10409:         $topurl=&declutter(
1.638     albertel 10410:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10411:                           );
                   10412:     }
                   10413: # ----------------------------------------------------------- Write preferences
1.84      www      10414:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10415:                      ('description'              => $description,
                   10416:                       'url'                      => $topurl,
                   10417:                       'internal.creator'         => $env{'user.name'}.':'.
                   10418:                                                     $env{'user.domain'},
                   10419:                       'internal.created'         => $now,
                   10420:                       'internal.creationcontext' => $context)
                   10421:                     );
1.84      www      10422:     return '/'.$udom.'/'.$uname;
                   10423: }
                   10424: 
1.1011    raeburn  10425: # ------------------------------------------------------------------- Create ID
                   10426: sub generate_coursenum {
1.1038    raeburn  10427:     my ($udom,$crstype) = @_;
1.1011    raeburn  10428:     my $domdesc = &domain($udom);
                   10429:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10430:     my $first;
                   10431:     if ($crstype eq 'Community') {
                   10432:         $first = '0';
                   10433:     } else {
                   10434:         $first = int(1+rand(9)); 
                   10435:     } 
                   10436:     my $uname=$first.
1.1011    raeburn  10437:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10438:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10439:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10440: # ----------------------------------------------- Make sure that does not exist
                   10441:     my $uhome=&homeserver($uname,$udom,'true');
                   10442:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10443:         if ($crstype eq 'Community') {
                   10444:             $first = '0';
                   10445:         } else {
                   10446:             $first = int(1+rand(9));
                   10447:         }
                   10448:         $uname=$first.
1.1011    raeburn  10449:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10450:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10451:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10452:         $uhome=&homeserver($uname,$udom,'true');
                   10453:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10454:             return 'error: unable to generate unique course-ID';
                   10455:         }
                   10456:     }
                   10457:     return $uname;
                   10458: }
                   10459: 
1.813     albertel 10460: sub is_course {
1.1167    droeschl 10461:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10462:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10463:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10464:     my $uhome=&homeserver($cnum,$cdom);
                   10465:     my $iscourse;
                   10466:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10467:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10468:     } else {
                   10469:         my $hashid = $cdom.':'.$cnum;
                   10470:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10471:         unless (defined($cached)) {
                   10472:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10473:                                         $cnum,undef,undef,'.');
                   10474:             $iscourse = 0;
                   10475:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10476:                 $iscourse = 1;
                   10477:             }
                   10478:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10479:         }
                   10480:     }
                   10481:     return unless($iscourse);
1.1167    droeschl 10482:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10483: }
                   10484: 
1.1015    raeburn  10485: sub store_userdata {
                   10486:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10487:     my $result;
1.1016    raeburn  10488:     if ($datakey ne '') {
1.1013    raeburn  10489:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10490:             if ($udom eq '' || $uname eq '') {
                   10491:                 $udom = $env{'user.domain'};
                   10492:                 $uname = $env{'user.name'};
                   10493:             }
                   10494:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10495:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10496:                 $result = 'error: no_host';
                   10497:             } else {
                   10498:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10499:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10500: 
                   10501:                 my $namevalue='';
                   10502:                 foreach my $key (keys(%{$storehash})) {
                   10503:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10504:                 }
                   10505:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10506:                 unless ($namespace eq 'courserequests') {
                   10507:                     $datakey = &escape($datakey);
                   10508:                 }
1.1105    raeburn  10509:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10510:                                   $namevalue,$uhome);
1.1013    raeburn  10511:             }
                   10512:         } else {
                   10513:             $result = 'error: data to store was not a hash reference'; 
                   10514:         }
                   10515:     } else {
                   10516:         $result= 'error: invalid requestkey'; 
                   10517:     }
                   10518:     return $result;
                   10519: }
                   10520: 
1.21      www      10521: # ---------------------------------------------------------- Assign Custom Role
                   10522: 
                   10523: sub assigncustomrole {
1.957     raeburn  10524:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10525:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10526:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10527: }
                   10528: 
                   10529: # ----------------------------------------------------------------- Revoke Role
                   10530: 
                   10531: sub revokerole {
1.957     raeburn  10532:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10533:     my $now=time;
1.965     raeburn  10534:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10535: }
                   10536: 
                   10537: # ---------------------------------------------------------- Revoke Custom Role
                   10538: 
                   10539: sub revokecustomrole {
1.957     raeburn  10540:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10541:     my $now=time;
1.357     www      10542:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10543:            $deleteflag,$selfenroll,$context);
1.17      www      10544: }
                   10545: 
1.533     banghart 10546: # ------------------------------------------------------------ Disk usage
1.535     albertel 10547: sub diskusage {
1.955     raeburn  10548:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10549:     $directorypath =~ s/\/$//;
                   10550:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10551:                        .&escape($getpropath).':'.&escape($uname).':'
                   10552:                        .&escape($udom),homeserver($uname,$udom));
                   10553:     if ($listing eq 'unknown_cmd') {
                   10554:         if ($getpropath) {
                   10555:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10556:         }
                   10557:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10558:     }
1.514     albertel 10559:     return $listing;
1.512     banghart 10560: }
                   10561: 
1.566     banghart 10562: sub is_locked {
1.1096    raeburn  10563:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10564:     my @check;
                   10565:     my $is_locked;
1.1093    raeburn  10566:     push (@check,$file_name);
1.613     albertel 10567:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10568: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10569:     my ($tmp)=keys(%locked);
                   10570:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10571:     
1.566     banghart 10572:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10573:         $is_locked = 'false';
                   10574:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10575:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10576:                $is_locked = 'true';
1.1096    raeburn  10577:                if (ref($which) eq 'ARRAY') {
                   10578:                    push(@{$which},$entry);
                   10579:                } else {
                   10580:                    last;
                   10581:                }
1.745     raeburn  10582:            }
                   10583:        }
1.566     banghart 10584:     } else {
                   10585:         $is_locked = 'false';
                   10586:     }
1.1093    raeburn  10587:     return $is_locked;
1.566     banghart 10588: }
                   10589: 
1.759     albertel 10590: sub declutter_portfile {
                   10591:     my ($file) = @_;
1.833     albertel 10592:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10593:     return $file;
                   10594: }
                   10595: 
1.559     banghart 10596: # ------------------------------------------------------------- Mark as Read Only
                   10597: 
                   10598: sub mark_as_readonly {
                   10599:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10600:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10601:     my ($tmp)=keys(%current_permissions);
                   10602:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10603:     foreach my $file (@{$files}) {
1.759     albertel 10604: 	$file = &declutter_portfile($file);
1.561     banghart 10605:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10606:     }
1.613     albertel 10607:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10608:     return;
                   10609: }
                   10610: 
1.572     banghart 10611: # ------------------------------------------------------------Save Selected Files
                   10612: 
                   10613: sub save_selected_files {
                   10614:     my ($user, $path, @files) = @_;
                   10615:     my $filename = $user."savedfiles";
1.573     banghart 10616:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10617:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10618:     foreach my $file (@files) {
1.620     albertel 10619:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10620:     }
                   10621:     foreach my $file (@other_files) {
1.574     banghart 10622:         print (OUT $file."\n");
1.572     banghart 10623:     }
1.574     banghart 10624:     close (OUT);
1.572     banghart 10625:     return 'ok';
                   10626: }
                   10627: 
1.574     banghart 10628: sub clear_selected_files {
                   10629:     my ($user) = @_;
                   10630:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10631:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10632:     print (OUT undef);
                   10633:     close (OUT);
                   10634:     return ("ok");    
                   10635: }
                   10636: 
1.572     banghart 10637: sub files_in_path {
                   10638:     my ($user, $path) = @_;
                   10639:     my $filename = $user."savedfiles";
                   10640:     my %return_files;
1.1172.2.96  raeburn  10641:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10642:     while (my $line_in = <IN>) {
1.574     banghart 10643:         chomp ($line_in);
                   10644:         my @paths_and_file = split (m!/!, $line_in);
                   10645:         my $file_part = pop (@paths_and_file);
                   10646:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10647:         $path_part.='/';
                   10648:         my $path_and_file = $path_part.$file_part;
                   10649:         if ($path_part eq $path) {
                   10650:             $return_files{$file_part}= 'selected';
                   10651:         }
                   10652:     }
1.574     banghart 10653:     close (IN);
                   10654:     return (\%return_files);
1.572     banghart 10655: }
                   10656: 
                   10657: # called in portfolio select mode, to show files selected NOT in current directory
                   10658: sub files_not_in_path {
                   10659:     my ($user, $path) = @_;
                   10660:     my $filename = $user."savedfiles";
                   10661:     my @return_files;
                   10662:     my $path_part;
1.1172.2.96  raeburn  10663:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10664:     while (my $line = <IN>) {
1.572     banghart 10665:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10666:         my @paths_and_file = split(m|/|, $line);
                   10667:         my $file_part = pop(@paths_and_file);
                   10668:         chomp($file_part);
                   10669:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10670:         $path_part .= '/';
                   10671:         my $path_and_file = $path_part.$file_part;
                   10672:         if ($path_part ne $path) {
1.800     albertel 10673:             push(@return_files, ($path_and_file));
1.572     banghart 10674:         }
                   10675:     }
1.800     albertel 10676:     close(OUT);
1.574     banghart 10677:     return (@return_files);
1.572     banghart 10678: }
                   10679: 
1.745     raeburn  10680: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10681: 
1.745     raeburn  10682: sub get_portfile_permissions {
                   10683:     my ($domain,$user) = @_;
1.613     albertel 10684:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10685:     my ($tmp)=keys(%current_permissions);
                   10686:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10687:     return \%current_permissions;
                   10688: }
                   10689: 
                   10690: #---------------------------------------------Get portfolio file access controls
                   10691: 
1.749     raeburn  10692: sub get_access_controls {
1.745     raeburn  10693:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10694:     my %access;
                   10695:     my $real_file = $file;
                   10696:     $file =~ s/\.meta$//;
1.745     raeburn  10697:     if (defined($file)) {
1.749     raeburn  10698:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10699:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10700:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10701:             }
                   10702:         }
1.745     raeburn  10703:     } else {
1.749     raeburn  10704:         foreach my $key (keys(%{$current_permissions})) {
                   10705:             if ($key =~ /\0accesscontrol$/) {
                   10706:                 if (defined($group)) {
                   10707:                     if ($key !~ m-^\Q$group\E/-) {
                   10708:                         next;
                   10709:                     }
                   10710:                 }
                   10711:                 my ($fullpath) = split(/\0/,$key);
                   10712:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10713:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10714:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10715:                     }
                   10716:                 }
                   10717:             }
                   10718:         }
                   10719:     }
                   10720:     return %access;
                   10721: }
                   10722: 
                   10723: sub modify_access_controls {
                   10724:     my ($file_name,$changes,$domain,$user)=@_;
                   10725:     my ($outcome,$deloutcome);
                   10726:     my %store_permissions;
                   10727:     my %new_values;
                   10728:     my %new_control;
                   10729:     my %translation;
                   10730:     my @deletions = ();
                   10731:     my $now = time;
                   10732:     if (exists($$changes{'activate'})) {
                   10733:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10734:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10735:             my $numnew = scalar(@newitems);
                   10736:             for (my $i=0; $i<$numnew; $i++) {
                   10737:                 my $newkey = $newitems[$i];
                   10738:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10739:                 if ($newkey =~ /^\d+:/) { 
                   10740:                     $newkey =~ s/^(\d+)/$newid/;
                   10741:                     $translation{$1} = $newid;
                   10742:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10743:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10744:                     $translation{$1} = $newid;
                   10745:                 }
1.749     raeburn  10746:                 $new_values{$file_name."\0".$newkey} = 
                   10747:                                           $$changes{'activate'}{$newitems[$i]};
                   10748:                 $new_control{$newkey} = $now;
                   10749:             }
                   10750:         }
                   10751:     }
                   10752:     my %todelete;
                   10753:     my %changed_items;
                   10754:     foreach my $action ('delete','update') {
                   10755:         if (exists($$changes{$action})) {
                   10756:             if (ref($$changes{$action}) eq 'HASH') {
                   10757:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10758:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10759:                     if ($action eq 'delete') { 
                   10760:                         $todelete{$itemnum} = 1;
                   10761:                     } else {
                   10762:                         $changed_items{$itemnum} = $key;
                   10763:                     }
                   10764:                 }
1.745     raeburn  10765:             }
                   10766:         }
1.749     raeburn  10767:     }
                   10768:     # get lock on access controls for file.
                   10769:     my $lockhash = {
                   10770:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10771:                                                        ':'.$env{'user.domain'},
                   10772:                    }; 
                   10773:     my $tries = 0;
                   10774:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10775:    
1.1172.2.79  raeburn  10776:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10777:         $tries ++;
1.1172.2.79  raeburn  10778:         sleep(0.1);
1.749     raeburn  10779:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10780:     }
                   10781:     if ($gotlock eq 'ok') {
                   10782:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10783:         my ($tmp)=keys(%curr_permissions);
                   10784:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10785:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10786:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10787:             if (ref($curr_controls) eq 'HASH') {
                   10788:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10789:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10790:                     if (defined($todelete{$itemnum})) {
                   10791:                         push(@deletions,$file_name."\0".$control_item);
                   10792:                     } else {
                   10793:                         if (defined($changed_items{$itemnum})) {
                   10794:                             $new_control{$changed_items{$itemnum}} = $now;
                   10795:                             push(@deletions,$file_name."\0".$control_item);
                   10796:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10797:                         } else {
                   10798:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10799:                         }
                   10800:                     }
1.745     raeburn  10801:                 }
                   10802:             }
                   10803:         }
1.970     raeburn  10804:         my ($group);
                   10805:         if (&is_course($domain,$user)) {
                   10806:             ($group,my $file) = split(/\//,$file_name,2);
                   10807:         }
1.749     raeburn  10808:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10809:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10810:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10811:         #  remove lock
                   10812:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10813:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10814:         my $sqlresult =
1.970     raeburn  10815:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10816:                                     $group);
1.749     raeburn  10817:     } else {
                   10818:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10819:     }
1.749     raeburn  10820:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10821: }
                   10822: 
1.827     raeburn  10823: sub make_public_indefinitely {
                   10824:     my ($requrl) = @_;
                   10825:     my $now = time;
                   10826:     my $action = 'activate';
                   10827:     my $aclnum = 0;
                   10828:     if (&is_portfolio_url($requrl)) {
                   10829:         my (undef,$udom,$unum,$file_name,$group) =
                   10830:             &parse_portfolio_url($requrl);
                   10831:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10832:         my %access_controls = &get_access_controls($current_perms,
                   10833:                                                    $group,$file_name);
                   10834:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10835:             my ($num,$scope,$end,$start) = 
                   10836:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10837:             if ($scope eq 'public') {
                   10838:                 if ($start <= $now && $end == 0) {
                   10839:                     $action = 'none';
                   10840:                 } else {
                   10841:                     $action = 'update';
                   10842:                     $aclnum = $num;
                   10843:                 }
                   10844:                 last;
                   10845:             }
                   10846:         }
                   10847:         if ($action eq 'none') {
                   10848:              return 'ok';
                   10849:         } else {
                   10850:             my %changes;
                   10851:             my $newend = 0;
                   10852:             my $newstart = $now;
                   10853:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10854:             $changes{$action}{$newkey} = {
                   10855:                 type => 'public',
                   10856:                 time => {
                   10857:                     start => $newstart,
                   10858:                     end   => $newend,
                   10859:                 },
                   10860:             };
                   10861:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10862:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10863:             return $outcome;
                   10864:         }
                   10865:     } else {
                   10866:         return 'invalid';
                   10867:     }
                   10868: }
                   10869: 
1.745     raeburn  10870: #------------------------------------------------------Get Marked as Read Only
                   10871: 
                   10872: sub get_marked_as_readonly {
                   10873:     my ($domain,$user,$what,$group) = @_;
                   10874:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10875:     my @readonly_files;
1.629     banghart 10876:     my $cmp1=$what;
                   10877:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10878:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10879:         if (defined($group)) {
                   10880:             if ($file_name !~ m-^\Q$group\E/-) {
                   10881:                 next;
                   10882:             }
                   10883:         }
1.561     banghart 10884:         if (ref($value) eq "ARRAY"){
                   10885:             foreach my $stored_what (@{$value}) {
1.629     banghart 10886:                 my $cmp2=$stored_what;
1.759     albertel 10887:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10888:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10889:                 }
1.629     banghart 10890:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10891:                     push(@readonly_files, $file_name);
1.745     raeburn  10892:                     last;
1.563     banghart 10893:                 } elsif (!defined($what)) {
                   10894:                     push(@readonly_files, $file_name);
1.745     raeburn  10895:                     last;
1.561     banghart 10896:                 }
                   10897:             }
1.745     raeburn  10898:         }
1.561     banghart 10899:     }
                   10900:     return @readonly_files;
                   10901: }
1.577     banghart 10902: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10903: 
1.577     banghart 10904: sub get_marked_as_readonly_hash {
1.745     raeburn  10905:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10906:     my %readonly_files;
1.745     raeburn  10907:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10908:         if (defined($group)) {
                   10909:             if ($file_name !~ m-^\Q$group\E/-) {
                   10910:                 next;
                   10911:             }
                   10912:         }
1.577     banghart 10913:         if (ref($value) eq "ARRAY"){
                   10914:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10915:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10916:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10917:                         if ($lock_descriptor eq 'graded') {
                   10918:                             $readonly_files{$file_name} = 'graded';
                   10919:                         } elsif ($lock_descriptor eq 'handback') {
                   10920:                             $readonly_files{$file_name} = 'handback';
                   10921:                         } else {
                   10922:                             if (!exists($readonly_files{$file_name})) {
                   10923:                                 $readonly_files{$file_name} = 'locked';
                   10924:                             }
                   10925:                         }
1.745     raeburn  10926:                     }
1.750     banghart 10927:                 } 
1.577     banghart 10928:             }
                   10929:         } 
                   10930:     }
                   10931:     return %readonly_files;
                   10932: }
1.559     banghart 10933: # ------------------------------------------------------------ Unmark as Read Only
                   10934: 
                   10935: sub unmark_as_readonly {
1.629     banghart 10936:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10937:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10938:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10939:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10940:     my $symb_crs = $what;
                   10941:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10942:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10943:     my ($tmp)=keys(%current_permissions);
                   10944:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10945:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10946:     foreach my $file (@readonly_files) {
1.759     albertel 10947: 	my $clean_file = &declutter_portfile($file);
                   10948: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10949: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10950:         my @new_locks;
                   10951:         my @del_keys;
                   10952:         if (ref($current_locks) eq "ARRAY"){
                   10953:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10954:                 my $compare=$locker;
1.749     raeburn  10955:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10956:                     $compare=join('',@{$locker});
1.746     raeburn  10957:                     if ($compare ne $symb_crs) {
                   10958:                         push(@new_locks, $locker);
                   10959:                     }
1.563     banghart 10960:                 }
                   10961:             }
1.650     albertel 10962:             if (scalar(@new_locks) > 0) {
1.563     banghart 10963:                 $current_permissions{$file} = \@new_locks;
                   10964:             } else {
                   10965:                 push(@del_keys, $file);
1.613     albertel 10966:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10967:                 delete($current_permissions{$file});
1.563     banghart 10968:             }
                   10969:         }
1.561     banghart 10970:     }
1.613     albertel 10971:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10972:     return;
                   10973: }
1.512     banghart 10974: 
1.17      www      10975: # ------------------------------------------------------------ Directory lister
                   10976: 
                   10977: sub dirlist {
1.955     raeburn  10978:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10979:     $uri=~s/^\///;
                   10980:     $uri=~s/\/$//;
1.253     stredwic 10981:     my ($udom, $uname);
1.955     raeburn  10982:     if ($getuserdir) {
1.253     stredwic 10983:         $udom = $userdomain;
                   10984:         $uname = $username;
1.955     raeburn  10985:     } else {
                   10986:         (undef,$udom,$uname)=split(/\//,$uri);
                   10987:         if(defined($userdomain)) {
                   10988:             $udom = $userdomain;
                   10989:         }
                   10990:         if(defined($username)) {
                   10991:             $uname = $username;
                   10992:         }
1.253     stredwic 10993:     }
1.955     raeburn  10994:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10995: 
1.955     raeburn  10996:     $dirRoot = $perlvar{'lonDocRoot'};
                   10997:     if (defined($getpropath)) {
                   10998:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10999:         $dirRoot =~ s/\/$//;
1.955     raeburn  11000:     } elsif (defined($getuserdir)) {
                   11001:         my $subdir=$uname.'__';
                   11002:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11003:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11004:                    ."/$udom/$subdir/$uname";
                   11005:     } elsif (defined($alternateRoot)) {
                   11006:         $dirRoot = $alternateRoot;
1.751     banghart 11007:     }
1.253     stredwic 11008: 
                   11009:     if($udom) {
                   11010:         if($uname) {
1.1135    raeburn  11011:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11012:             if ($uhome eq 'no_host') {
                   11013:                 return ([],'no_host');
                   11014:             }
1.955     raeburn  11015:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11016:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11017:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11018:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11019:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11020:             } else {
                   11021:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11022:             }
1.605     matthew  11023:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11024:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11025:                 @listing_results = split(/:/,$listing);
                   11026:             } else {
                   11027:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11028:             }
1.1135    raeburn  11029:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11030:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11031:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11032:                 return ([],$listing);
                   11033:             } else {
                   11034:                 return (\@listing_results);
1.1135    raeburn  11035:             }
1.955     raeburn  11036:         } elsif(!$alternateRoot) {
1.1136    raeburn  11037:             my (%allusers,%listerror);
1.841     albertel 11038: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11039:  	    foreach my $tryserver (keys(%servers)) {
                   11040:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11041:                                   &escape($udom),$tryserver);
                   11042:                 if ($listing eq 'unknown_cmd') {
                   11043: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11044: 				      $udom, $tryserver);
                   11045:                 } else {
                   11046:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11047:                 }
1.841     albertel 11048: 		if ($listing eq 'unknown_cmd') {
                   11049: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11050: 				      $udom, $tryserver);
                   11051: 		    @listing_results = split(/:/,$listing);
                   11052: 		} else {
                   11053: 		    @listing_results =
                   11054: 			map { &unescape($_); } split(/:/,$listing);
                   11055: 		}
1.1136    raeburn  11056:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11057:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11058:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11059:                     $listerror{$tryserver} = $listing;
                   11060:                 } else {
1.841     albertel 11061: 		    foreach my $line (@listing_results) {
                   11062: 			my ($entry) = split(/&/,$line,2);
                   11063: 			$allusers{$entry} = 1;
                   11064: 		    }
                   11065: 		}
1.253     stredwic 11066:             }
1.1136    raeburn  11067:             my @alluserslist=();
1.800     albertel 11068:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11069:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11070:             }
1.1172.2.80  raeburn  11071:             if (!%listerror) {
                   11072:                 # no errors
                   11073:                 return (\@alluserslist);
                   11074:             } elsif (scalar(keys(%servers)) == 1) {
                   11075:                 # one library server, one error
                   11076:                 my ($key) = keys(%listerror);
                   11077:                 return (\@alluserslist, $listerror{$key});
                   11078:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11079:                 # con_lost indicates that we might miss data from at least one
                   11080:                 # library server
                   11081:                 return (\@alluserslist, 'con_lost');
                   11082:             } else {
                   11083:                 # multiple library servers and no con_lost -> data should be
                   11084:                 # complete.
                   11085:                 return (\@alluserslist);
                   11086:             }
                   11087: 
1.253     stredwic 11088:         } else {
1.1136    raeburn  11089:             return ([],'missing username');
1.253     stredwic 11090:         }
1.955     raeburn  11091:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11092:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11093:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11094:         return (\@all_domains);
1.955     raeburn  11095:     } else {
1.1136    raeburn  11096:         return ([],'missing domain');
1.275     stredwic 11097:     }
                   11098: }
                   11099: 
                   11100: # --------------------------------------------- GetFileTimestamp
                   11101: # This function utilizes dirlist and returns the date stamp for
                   11102: # when it was last modified.  It will also return an error of -1
                   11103: # if an error occurs
                   11104: 
                   11105: sub GetFileTimestamp {
1.955     raeburn  11106:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11107:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11108:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11109:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11110:                                     undef,$getuserdir);
                   11111:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11112:         return -1;
                   11113:     }
                   11114:     if (ref($fileref) eq 'ARRAY') {
                   11115:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11116:         # @stats contains first the filename, then the stat output
                   11117:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11118:     } else {
                   11119:         return -1;
1.253     stredwic 11120:     }
1.26      www      11121: }
                   11122: 
1.712     albertel 11123: sub stat_file {
                   11124:     my ($uri) = @_;
1.787     albertel 11125:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11126: 
1.955     raeburn  11127:     my ($udom,$uname,$file);
1.712     albertel 11128:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11129: 	($udom,$uname,$file) =
1.811     albertel 11130: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11131: 	$file = 'userfiles/'.$file;
                   11132:     }
                   11133:     if ($uri =~ m-^/res/-) {
                   11134: 	($udom,$uname) = 
1.807     albertel 11135: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11136: 	$file = $uri;
                   11137:     }
                   11138: 
                   11139:     if (!$udom || !$uname || !$file) {
                   11140: 	# unable to handle the uri
                   11141: 	return ();
                   11142:     }
1.956     raeburn  11143:     my $getpropath;
                   11144:     if ($file =~ /^userfiles\//) {
                   11145:         $getpropath = 1;
                   11146:     }
1.1136    raeburn  11147:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11148:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11149:         return ();
                   11150:     } else {
                   11151:         if (ref($listref) eq 'ARRAY') {
                   11152:             my @stats = split('&',$listref->[0]);
                   11153: 	    shift(@stats); #filename is first
                   11154: 	    return @stats;
                   11155:         }
1.712     albertel 11156:     }
                   11157:     return ();
                   11158: }
                   11159: 
1.26      www      11160: # -------------------------------------------------------- Value of a Condition
                   11161: 
1.713     albertel 11162: # gets the value of a specific preevaluated condition
                   11163: #    stored in the string  $env{user.state.<cid>}
                   11164: # or looks up a condition reference in the bighash and if if hasn't
                   11165: # already been evaluated recurses into docondval to get the value of
                   11166: # the condition, then memoizing it to 
                   11167: #   $env{user.state.<cid>.<condition>}
1.40      www      11168: sub directcondval {
                   11169:     my $number=shift;
1.620     albertel 11170:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11171: 	&Apache::lonuserstate::evalstate();
                   11172:     }
1.713     albertel 11173:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11174: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11175:     } elsif ($number =~ /^_/) {
                   11176: 	my $sub_condition;
                   11177: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11178: 		&GDBM_READER(),0640)) {
                   11179: 	    $sub_condition=$bighash{'conditions'.$number};
                   11180: 	    untie(%bighash);
                   11181: 	}
                   11182: 	my $value = &docondval($sub_condition);
1.949     raeburn  11183: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11184: 	return $value;
                   11185:     }
1.620     albertel 11186:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11187:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11188:     } else {
                   11189:        return 2;
                   11190:     }
                   11191: }
                   11192: 
1.713     albertel 11193: # get the collection of conditions for this resource
1.26      www      11194: sub condval {
                   11195:     my $condidx=shift;
1.54      www      11196:     my $allpathcond='';
1.713     albertel 11197:     foreach my $cond (split(/\|/,$condidx)) {
                   11198: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11199: 	    $allpathcond.=
                   11200: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11201: 	}
1.191     harris41 11202:     }
1.54      www      11203:     $allpathcond=~s/\|$//;
1.713     albertel 11204:     return &docondval($allpathcond);
                   11205: }
                   11206: 
                   11207: #evaluates an expression of conditions
                   11208: sub docondval {
                   11209:     my ($allpathcond) = @_;
                   11210:     my $result=0;
                   11211:     if ($env{'request.course.id'}
                   11212: 	&& defined($allpathcond)) {
                   11213: 	my $operand='|';
                   11214: 	my @stack;
                   11215: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11216: 	    if ($chunk eq '(') {
                   11217: 		push @stack,($operand,$result);
                   11218: 	    } elsif ($chunk eq ')') {
                   11219: 		my $before=pop @stack;
                   11220: 		if (pop @stack eq '&') {
                   11221: 		    $result=$result>$before?$before:$result;
                   11222: 		} else {
                   11223: 		    $result=$result>$before?$result:$before;
                   11224: 		}
                   11225: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11226: 		$operand=$chunk;
                   11227: 	    } else {
                   11228: 		my $new=directcondval($chunk);
                   11229: 		if ($operand eq '&') {
                   11230: 		    $result=$result>$new?$new:$result;
                   11231: 		} else {
                   11232: 		    $result=$result>$new?$result:$new;
                   11233: 		}
                   11234: 	    }
                   11235: 	}
1.26      www      11236:     }
                   11237:     return $result;
1.421     albertel 11238: }
                   11239: 
                   11240: # ---------------------------------------------------- Devalidate courseresdata
                   11241: 
                   11242: sub devalidatecourseresdata {
                   11243:     my ($coursenum,$coursedomain)=@_;
                   11244:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11245:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11246: }
                   11247: 
1.763     www      11248: 
1.200     www      11249: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11250: #
                   11251: #  Parameters:
                   11252: #      $coursenum    - Number of the course.
                   11253: #      $coursedomain - Domain at which the course was created.
                   11254: #  Returns:
                   11255: #     A hash of the course parameters along (I think) with timestamps
                   11256: #     and version info.
1.877     foxr     11257: 
1.624     albertel 11258: sub get_courseresdata {
                   11259:     my ($coursenum,$coursedomain)=@_;
1.200     www      11260:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11261:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11262:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11263:     my %dumpreply;
1.417     albertel 11264:     unless (defined($cached)) {
1.624     albertel 11265: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11266: 	$result=\%dumpreply;
1.251     albertel 11267: 	my ($tmp) = keys(%dumpreply);
                   11268: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11269: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11270: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11271: 	    return $tmp;
1.416     albertel 11272: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11273: 	    $result=undef;
1.599     albertel 11274: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11275: 	}
                   11276:     }
1.624     albertel 11277:     return $result;
                   11278: }
                   11279: 
1.633     albertel 11280: sub devalidateuserresdata {
                   11281:     my ($uname,$udom)=@_;
                   11282:     my $hashid="$udom:$uname";
                   11283:     &devalidate_cache_new('userres',$hashid);
                   11284: }
                   11285: 
1.624     albertel 11286: sub get_userresdata {
                   11287:     my ($uname,$udom)=@_;
                   11288:     #most student don\'t have any data set, check if there is some data
                   11289:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11290: 
                   11291:     my $hashid="$udom:$uname";
                   11292:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11293:     if (!defined($cached)) {
                   11294: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11295: 	$result=\%resourcedata;
                   11296: 	&do_cache_new('userres',$hashid,$result,600);
                   11297:     }
                   11298:     my ($tmp)=keys(%$result);
                   11299:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11300: 	return $result;
                   11301:     }
                   11302:     #error 2 occurs when the .db doesn't exist
                   11303:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11304:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11305: 	    &logthis("<font color=\"blue\">WARNING:".
                   11306: 		     " Trying to get resource data for ".
                   11307: 		     $uname." at ".$udom.": ".
                   11308: 		     $tmp."</font>");
                   11309:         }
1.624     albertel 11310:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11311: 	#&EXT_cache_set($udom,$uname);
                   11312: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11313: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11314:     }
                   11315:     return $tmp;
                   11316: }
1.879     foxr     11317: #----------------------------------------------- resdata - return resource data
                   11318: #  Purpose:
                   11319: #    Return resource data for either users or for a course.
                   11320: #  Parameters:
                   11321: #     $name      - Course/user name.
                   11322: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11323:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11324: #     @which     - Array of names of resources desired.
                   11325: #  Returns:
                   11326: #     The value of the first reasource in @which that is found in the
                   11327: #     resource hash.
                   11328: #  Exceptional Conditions:
                   11329: #     If the $type passed in is not valid (not the string 'course' or 
                   11330: #     'user', an undefined  reference is returned.
                   11331: #     If none of the resources are found, an undef is returned
1.624     albertel 11332: sub resdata {
                   11333:     my ($name,$domain,$type,@which)=@_;
                   11334:     my $result;
                   11335:     if ($type eq 'course') {
                   11336: 	$result=&get_courseresdata($name,$domain);
                   11337:     } elsif ($type eq 'user') {
                   11338: 	$result=&get_userresdata($name,$domain);
                   11339:     }
                   11340:     if (!ref($result)) { return $result; }    
1.251     albertel 11341:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11342:20): 	if (defined($result->{$item->[0]})) {
                   11343:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11344:20):         }
1.250     albertel 11345:     }
1.291     albertel 11346:     return undef;
1.200     www      11347: }
                   11348: 
1.1172.2.118.  .1(raebu 11349:20): sub get_domain_ltitools {
                   11350:20):     my ($cdom) = @_;
                   11351:20):     my %ltitools;
                   11352:20):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11353:20):     if (defined($cached)) {
                   11354:20):         if (ref($result) eq 'HASH') {
                   11355:20):             %ltitools = %{$result};
                   11356:20):         }
                   11357:20):     } else {
                   11358:20):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11359:20):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11360:20):             %ltitools = %{$domconfig{'ltitools'}};
                   11361:20):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11362:20):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11363:20):                 foreach my $id (keys(%ltitools)) {
                   11364:20):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11365:20):                         foreach my $item ('key','secret') {
                   11366:20):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11367:20):                         }
                   11368:20):                     }
                   11369:20):                 }
                   11370:20):             }
                   11371:20):         }
                   11372:20):         my $cachetime = 24*60*60;
                   11373:20):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11374:20):     }
                   11375:20):     return %ltitools;
                   11376:20): }
                   11377:20): 
1.1172.2.31  raeburn  11378: sub get_numsuppfiles {
                   11379:     my ($cnum,$cdom,$ignorecache)=@_;
                   11380:     my $hashid=$cnum.':'.$cdom;
                   11381:     my ($suppcount,$cached);
                   11382:     unless ($ignorecache) {
                   11383:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11384:     }
                   11385:     unless (defined($cached)) {
                   11386:         my $chome=&homeserver($cnum,$cdom);
                   11387:         unless ($chome eq 'no_host') {
                   11388:             ($suppcount,my $errors) = (0,0);
                   11389:             my $suppmap = 'supplemental.sequence';
                   11390:             ($suppcount,$errors) =
                   11391:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11392:         }
                   11393:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11394:     }
                   11395:     return $suppcount;
                   11396: }
                   11397: 
1.379     matthew  11398: #
                   11399: # EXT resource caching routines
                   11400: #
                   11401: 
                   11402: sub clear_EXT_cache_status {
1.383     albertel 11403:     &delenv('cache.EXT.');
1.379     matthew  11404: }
                   11405: 
                   11406: sub EXT_cache_status {
                   11407:     my ($target_domain,$target_user) = @_;
1.383     albertel 11408:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11409:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11410:         # We know already the user has no data
                   11411:         return 1;
                   11412:     } else {
                   11413:         return 0;
                   11414:     }
                   11415: }
                   11416: 
                   11417: sub EXT_cache_set {
                   11418:     my ($target_domain,$target_user) = @_;
1.383     albertel 11419:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11420:     #&appenv({$cachename => time});
1.379     matthew  11421: }
                   11422: 
1.28      www      11423: # --------------------------------------------------------- Value of a Variable
1.58      www      11424: sub EXT {
1.715     albertel 11425: 
1.1172.2.28  raeburn  11426:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11427:     unless ($varname) { return ''; }
1.218     albertel 11428:     #get real user name/domain, courseid and symb
                   11429:     my $courseid;
1.359     albertel 11430:     my $publicuser;
1.427     www      11431:     if ($symbparm) {
                   11432: 	$symbparm=&get_symb_from_alias($symbparm);
                   11433:     }
1.218     albertel 11434:     if (!($uname && $udom)) {
1.790     albertel 11435:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11436:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11437:     } else {
1.620     albertel 11438: 	$courseid=$env{'request.course.id'};
1.218     albertel 11439:     }
1.48      www      11440:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11441:     my $rest;
1.320     albertel 11442:     if (defined($therest[0])) {
1.48      www      11443:        $rest=join('.',@therest);
                   11444:     } else {
                   11445:        $rest='';
                   11446:     }
1.320     albertel 11447: 
1.57      www      11448:     my $qualifierrest=$qualifier;
                   11449:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11450:     my $spacequalifierrest=$space;
                   11451:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11452:     if ($realm eq 'user') {
1.48      www      11453: # --------------------------------------------------------------- user.resource
                   11454: 	if ($space eq 'resource') {
1.651     albertel 11455: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11456: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11457: 		 &&
1.744     albertel 11458: 		 ($symbparm eq &symbread()) ) {	
                   11459: 		# if we are in the middle of processing the resource the
                   11460: 		# get the value we are planning on committing
                   11461:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11462:                     return $Apache::lonhomework::results{$qualifierrest};
                   11463:                 } else {
                   11464:                     return $Apache::lonhomework::history{$qualifierrest};
                   11465:                 }
1.335     albertel 11466: 	    } else {
1.359     albertel 11467: 		my %restored;
1.620     albertel 11468: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11469: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11470: 		} else {
                   11471: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11472: 		}
1.335     albertel 11473: 		return $restored{$qualifierrest};
                   11474: 	    }
1.48      www      11475: # ----------------------------------------------------------------- user.access
                   11476:         } elsif ($space eq 'access') {
1.218     albertel 11477: 	    # FIXME - not supporting calls for a specific user
1.48      www      11478:             return &allowed($qualifier,$rest);
                   11479: # ------------------------------------------ user.preferences, user.environment
                   11480:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11481: 	    if (($uname eq $env{'user.name'}) &&
                   11482: 		($udom eq $env{'user.domain'})) {
                   11483: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11484: 	    } else {
1.359     albertel 11485: 		my %returnhash;
                   11486: 		if (!$publicuser) {
                   11487: 		    %returnhash=&userenvironment($udom,$uname,
                   11488: 						 $qualifierrest);
                   11489: 		}
1.218     albertel 11490: 		return $returnhash{$qualifierrest};
                   11491: 	    }
1.48      www      11492: # ----------------------------------------------------------------- user.course
                   11493:         } elsif ($space eq 'course') {
1.218     albertel 11494: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11495:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11496: # ------------------------------------------------------------------- user.role
                   11497:         } elsif ($space eq 'role') {
1.218     albertel 11498: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11499:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11500:             if ($qualifier eq 'value') {
                   11501: 		return $role;
                   11502:             } elsif ($qualifier eq 'extent') {
                   11503:                 return $where;
                   11504:             }
                   11505: # ----------------------------------------------------------------- user.domain
                   11506:         } elsif ($space eq 'domain') {
1.218     albertel 11507:             return $udom;
1.48      www      11508: # ------------------------------------------------------------------- user.name
                   11509:         } elsif ($space eq 'name') {
1.218     albertel 11510:             return $uname;
1.48      www      11511: # ---------------------------------------------------- Any other user namespace
1.29      www      11512:         } else {
1.359     albertel 11513: 	    my %reply;
                   11514: 	    if (!$publicuser) {
                   11515: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11516: 	    }
                   11517: 	    return $reply{$qualifierrest};
1.48      www      11518:         }
1.236     www      11519:     } elsif ($realm eq 'query') {
                   11520: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11521:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11522: 						[$spacequalifierrest]);
1.620     albertel 11523: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11524:    } elsif ($realm eq 'request') {
1.48      www      11525: # ------------------------------------------------------------- request.browser
                   11526:         if ($space eq 'browser') {
1.1145    bisitz   11527:             return $env{'browser.'.$qualifier};
1.57      www      11528: # ------------------------------------------------------------ request.filename
                   11529:         } else {
1.620     albertel 11530:             return $env{'request.'.$spacequalifierrest};
1.29      www      11531:         }
1.28      www      11532:     } elsif ($realm eq 'course') {
1.48      www      11533: # ---------------------------------------------------------- course.description
1.620     albertel 11534:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11535:     } elsif ($realm eq 'resource') {
1.165     www      11536: 
1.620     albertel 11537: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11538: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11539: 	}
1.693     albertel 11540: 
1.1172.2.30  raeburn  11541:         if ($qualifier eq '') {
                   11542: 	    if ($space eq 'title') {
                   11543: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11544: 	        return &gettitle($symbparm);
                   11545: 	    }
1.693     albertel 11546: 	
1.1172.2.30  raeburn  11547: 	    if ($space eq 'map') {
                   11548: 	        my ($map) = &decode_symb($symbparm);
                   11549: 	        return &symbread($map);
                   11550: 	    }
                   11551:             if ($space eq 'maptitle') {
                   11552:                 my ($map) = &decode_symb($symbparm);
                   11553:                 return &gettitle($map);
                   11554:             }
                   11555: 	    if ($space eq 'filename') {
                   11556: 	        if ($symbparm) {
                   11557: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11558: 	        }
                   11559: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11560: 	    }
1.1172.2.30  raeburn  11561: 
                   11562:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11563:                 if ($space eq 'visibleparts') {
                   11564:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11565:                     my $item;
                   11566:                     if (ref($navmap)) {
                   11567:                         my $res = $navmap->getBySymb($symbparm);
                   11568:                         my $parts = $res->parts();
                   11569:                         if (ref($parts) eq 'ARRAY') {
                   11570:                             $item = join(',',@{$parts});
                   11571:                         }
                   11572:                         undef($navmap);
                   11573:                     }
                   11574:                     return $item;
                   11575:                 }
                   11576:             }
                   11577:         }
1.693     albertel 11578: 
                   11579: 	my ($section, $group, @groups);
1.593     albertel 11580: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11581:         if (($courseid eq '') && ($cid)) {
                   11582:             $courseid = $cid;
                   11583:         }
                   11584: 	if (($symbparm && $courseid) && 
                   11585: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11586: 
1.218     albertel 11587: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11588: 
1.60      www      11589: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11590: 	    my $symbp=$symbparm;
1.735     albertel 11591: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11592: 
                   11593: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11594: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11595: 
1.620     albertel 11596: 	    if (($env{'user.name'} eq $uname) &&
                   11597: 		($env{'user.domain'} eq $udom)) {
                   11598: 		$section=$env{'request.course.sec'};
1.733     raeburn  11599:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11600:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11601: 	    } else {
1.539     albertel 11602: 		if (! defined($usection)) {
1.551     albertel 11603: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11604: 		} else {
                   11605: 		    $section = $usection;
                   11606: 		}
1.733     raeburn  11607:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11608: 	    }
                   11609: 
                   11610: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11611: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11612: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11613: 
1.593     albertel 11614: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11615: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11616: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11617: 
1.60      www      11618: # ----------------------------------------------------------- first, check user
1.624     albertel 11619: 
                   11620: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11621: 				       ([$courselevelr,'resource'],
                   11622: 					[$courselevelm,'map'     ],
                   11623: 					[$courselevel, 'course'  ]));
1.931     albertel 11624: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11625: 
1.594     albertel 11626: # ------------------------------------------------ second, check some of course
1.684     raeburn  11627:             my $coursereply;
1.691     raeburn  11628:             if (@groups > 0) {
                   11629:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11630:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11631:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11632:             }
1.96      www      11633: 
1.684     raeburn  11634: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11635: 				  $env{'course.'.$courseid.'.domain'},
                   11636: 				  'course',
                   11637: 				  ([$seclevelr,   'resource'],
                   11638: 				   [$seclevelm,   'map'     ],
                   11639: 				   [$seclevel,    'course'  ],
                   11640: 				   [$courselevelr,'resource']));
                   11641: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11642: 
1.60      www      11643: # ------------------------------------------------------ third, check map parms
1.218     albertel 11644: 	    my %parmhash=();
                   11645: 	    my $thisparm='';
                   11646: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11647: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11648: 		    &GDBM_READER(),0640)) {
1.218     albertel 11649: 		$thisparm=$parmhash{$symbparm};
                   11650: 		untie(%parmhash);
                   11651: 	    }
1.927     albertel 11652: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11653: 	}
1.594     albertel 11654: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11655: 
1.218     albertel 11656: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11657: 	my $filename;
                   11658: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11659: 	if ($symbparm) {
1.409     www      11660: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11661: 	} else {
1.620     albertel 11662: 	    $filename=$env{'request.filename'};
1.282     albertel 11663: 	}
                   11664: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11665: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11666: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11667: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11668: 
1.927     albertel 11669: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11670: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11671: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11672: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11673: 				     $env{'course.'.$courseid.'.domain'},
                   11674: 				     'course',
1.927     albertel 11675: 				     ([$courselevelm,'map'   ],
                   11676: 				      [$courselevel, 'course']));
                   11677: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11678: 	}
1.145     www      11679: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11680: 	unless ($space eq '0') {
1.336     albertel 11681: 	    my @parts=split(/_/,$space);
                   11682: 	    my $id=pop(@parts);
                   11683: 	    my $part=join('_',@parts);
                   11684: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11685: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11686: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11687: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11688: 	}
1.395     albertel 11689: 	if ($recurse) { return undef; }
                   11690: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11691: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11692: # ---------------------------------------------------- Any other user namespace
                   11693:     } elsif ($realm eq 'environment') {
                   11694: # ----------------------------------------------------------------- environment
1.620     albertel 11695: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11696: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11697: 	} else {
1.770     albertel 11698: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11699: 		return '';
                   11700: 	    }
1.219     albertel 11701: 	    my %returnhash=&userenvironment($udom,$uname,
                   11702: 					    $spacequalifierrest);
                   11703: 	    return $returnhash{$spacequalifierrest};
                   11704: 	}
1.28      www      11705:     } elsif ($realm eq 'system') {
1.48      www      11706: # ----------------------------------------------------------------- system.time
                   11707: 	if ($space eq 'time') {
                   11708: 	    return time;
                   11709:         }
1.696     albertel 11710:     } elsif ($realm eq 'server') {
                   11711: # ----------------------------------------------------------------- system.time
                   11712: 	if ($space eq 'name') {
                   11713: 	    return $ENV{'SERVER_NAME'};
                   11714:         }
1.28      www      11715:     }
1.48      www      11716:     return '';
1.61      www      11717: }
                   11718: 
1.927     albertel 11719: sub get_reply {
                   11720:     my ($reply_value) = @_;
1.940     raeburn  11721:     if (ref($reply_value) eq 'ARRAY') {
                   11722:         if (wantarray) {
                   11723: 	    return @$reply_value;
                   11724:         }
                   11725:         return $reply_value->[0];
                   11726:     } else {
                   11727:         return $reply_value;
1.927     albertel 11728:     }
                   11729: }
                   11730: 
1.691     raeburn  11731: sub check_group_parms {
                   11732:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11733:     my @groupitems = ();
                   11734:     my $resultitem;
1.927     albertel 11735:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11736:     foreach my $group (@{$groups}) {
                   11737:         foreach my $level (@levels) {
1.927     albertel 11738:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11739:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11740:         }
                   11741:     }
                   11742:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11743:                             $env{'course.'.$courseid.'.domain'},
                   11744:                                      'course',@groupitems);
                   11745:     return $coursereply;
                   11746: }
                   11747: 
                   11748: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11749:     my ($courseid,@groups) = @_;
                   11750:     @groups = sort(@groups);
1.691     raeburn  11751:     return @groups;
                   11752: }
                   11753: 
1.395     albertel 11754: sub packages_tab_default {
                   11755:     my ($uri,$varname)=@_;
                   11756:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11757: 
                   11758:     my (@extension,@specifics,$do_default);
                   11759:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11760: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11761: 	if ($pack_type eq 'default') {
                   11762: 	    $do_default=1;
                   11763: 	} elsif ($pack_type eq 'extension') {
                   11764: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11765: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11766: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11767: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11768: 	}
                   11769:     }
                   11770:     # first look for a package that matches the requested part id
                   11771:     foreach my $package (@specifics) {
                   11772: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11773: 	next if ($pack_part ne $part);
                   11774: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11775: 	    return $packagetab{"$pack_type&$name&default"};
                   11776: 	}
                   11777:     }
                   11778:     # look for any possible matching non extension_ package
                   11779:     foreach my $package (@specifics) {
                   11780: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11781: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11782: 	    return $packagetab{"$pack_type&$name&default"};
                   11783: 	}
1.585     albertel 11784: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11785: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11786: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11787: 	}
                   11788:     }
1.738     albertel 11789:     # look for any posible extension_ match
                   11790:     foreach my $package (@extension) {
                   11791: 	my ($package,$pack_type)=@{$package};
                   11792: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11793: 	    return $packagetab{"$pack_type&$name&default"};
                   11794: 	}
                   11795: 	if (defined($packagetab{$package."&$name&default"})) {
                   11796: 	    return $packagetab{$package."&$name&default"};
                   11797: 	}
                   11798:     }
                   11799:     # look for a global default setting
                   11800:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11801: 	return $packagetab{"default&$name&default"};
                   11802:     }
1.395     albertel 11803:     return undef;
                   11804: }
                   11805: 
1.334     albertel 11806: sub add_prefix_and_part {
                   11807:     my ($prefix,$part)=@_;
                   11808:     my $keyroot;
                   11809:     if (defined($prefix) && $prefix !~ /^__/) {
                   11810: 	# prefix that has a part already
                   11811: 	$keyroot=$prefix;
                   11812:     } elsif (defined($prefix)) {
                   11813: 	# prefix that is missing a part
                   11814: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11815:     } else {
                   11816: 	# no prefix at all
                   11817: 	if (defined($part)) { $keyroot='_'.$part; }
                   11818:     }
                   11819:     return $keyroot;
                   11820: }
                   11821: 
1.71      www      11822: # ---------------------------------------------------------------- Get metadata
                   11823: 
1.599     albertel 11824: my %metaentry;
1.1070    www      11825: my %importedpartids;
1.1172.2.99  raeburn  11826: my %importedrespids;
1.71      www      11827: sub metadata {
1.176     www      11828:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11829:     $uri=&declutter($uri);
1.288     albertel 11830:     # if it is a non metadata possible uri return quickly
1.529     albertel 11831:     if (($uri eq '') || 
                   11832: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11833:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11834:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11835: 	return undef;
                   11836:     }
1.1172.2.49  raeburn  11837:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11838: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11839: 	return undef;
1.288     albertel 11840:     }
1.73      www      11841:     my $filename=$uri;
                   11842:     $uri=~s/\.meta$//;
1.172     www      11843: #
                   11844: # Is the metadata already cached?
1.177     www      11845: # Look at timestamp of caching
1.172     www      11846: # Everything is cached by the main uri, libraries are never directly cached
                   11847: #
1.428     albertel 11848:     if (!defined($liburi)) {
1.599     albertel 11849: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11850: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11851:     }
                   11852:     {
1.1069    www      11853: # Imported parts would go here
1.1172.2.99  raeburn  11854:         my @origfiletagids=();
1.1069    www      11855:         my $importedparts=0;
1.1172.2.99  raeburn  11856: 
                   11857: # Imported responseids would go here
                   11858:         my $importedresponses=0;
1.172     www      11859: #
                   11860: # Is this a recursive call for a library?
                   11861: #
1.599     albertel 11862: #	if (! exists($metacache{$uri})) {
                   11863: #	    $metacache{$uri}={};
                   11864: #	}
1.924     albertel 11865: 	my $cachetime = 60*60;
1.171     www      11866:         if ($liburi) {
                   11867: 	    $liburi=&declutter($liburi);
                   11868:             $filename=$liburi;
1.401     bowersj2 11869:         } else {
1.599     albertel 11870: 	    &devalidate_cache_new('meta',$uri);
                   11871: 	    undef(%metaentry);
1.401     bowersj2 11872: 	}
1.140     www      11873:         my %metathesekeys=();
1.73      www      11874:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11875: 	my $metastring;
1.1140    www      11876: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11877: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11878: 	    $metastring = 
1.929     albertel 11879: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11880: 					  ('grade_target' => 'meta'));
                   11881: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11882: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11883:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11884: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11885: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11886: 	    $metastring=&getfile($file);
1.489     albertel 11887: 	}
1.208     albertel 11888:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11889:         my $token;
1.140     www      11890:         undef %metathesekeys;
1.71      www      11891:         while ($token=$parser->get_token) {
1.339     albertel 11892: 	    if ($token->[0] eq 'S') {
                   11893: 		if (defined($token->[2]->{'package'})) {
1.172     www      11894: #
                   11895: # This is a package - get package info
                   11896: #
1.339     albertel 11897: 		    my $package=$token->[2]->{'package'};
                   11898: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11899: 		    if (defined($token->[2]->{'id'})) { 
                   11900: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11901: 		    }
1.599     albertel 11902: 		    if ($metaentry{':packages'}) {
                   11903: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11904: 		    } else {
1.599     albertel 11905: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11906: 		    }
1.736     albertel 11907: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11908: 			my $part=$keyroot;
                   11909: 			$part=~s/^\_//;
1.736     albertel 11910: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11911: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11912: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11913: 			    # ignore package.tab specified default values
                   11914:                             # here &package_tab_default() will fetch those
                   11915: 			    if ($subp eq 'default') { next; }
1.736     albertel 11916: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11917: 			    my $unikey;
                   11918: 			    if ($pack =~ /_0$/) {
                   11919: 				$unikey='parameter_0_'.$name;
                   11920: 				$part=0;
                   11921: 			    } else {
                   11922: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11923: 			    }
1.339     albertel 11924: 			    if ($subp eq 'display') {
                   11925: 				$value.=' [Part: '.$part.']';
                   11926: 			    }
1.599     albertel 11927: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11928: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11929: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11930: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11931: 			    }
1.599     albertel 11932: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11933: 				$metaentry{':'.$unikey}=
                   11934: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11935: 			    }
1.339     albertel 11936: 			}
                   11937: 		    }
                   11938: 		} else {
1.172     www      11939: #
                   11940: # This is not a package - some other kind of start tag
1.339     albertel 11941: #
                   11942: 		    my $entry=$token->[1];
1.1068    www      11943: 		    my $unikey='';
1.175     www      11944: 
1.339     albertel 11945: 		    if ($entry eq 'import') {
1.175     www      11946: #
                   11947: # Importing a library here
1.339     albertel 11948: #
1.1067    www      11949:                         my $location=$parser->get_text('/import');
                   11950:                         my $dir=$filename;
                   11951:                         $dir=~s|[^/]*$||;
                   11952:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11953: 
                   11954:                         my $importid=$token->[2]->{'id'};
1.1068    www      11955:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11956: #
                   11957: # Check metadata for imported file to
                   11958: # see if it contained response items
                   11959: #
                   11960:                         my %currmetaentry = %metaentry;
                   11961:                         my $libresponseorder = &metadata($location,'responseorder');
                   11962:                         my $origfile;
                   11963:                         if ($libresponseorder ne '') {
                   11964:                             if ($#origfiletagids<0) {
                   11965:                                 undef(%importedrespids);
                   11966:                                 undef(%importedpartids);
                   11967:                             }
                   11968:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11969:                             if (@{$importedrespids{$importid}} > 0) {
                   11970:                                 $importedresponses = 1;
                   11971: # We need to get the original file and the imported file to get the response order correct
                   11972: # Load and inspect original file
                   11973:                                 if ($#origfiletagids<0) {
                   11974:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11975:                                     $origfile=&getfile($origfilelocation);
                   11976:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11977:                                 }
                   11978:                             }
                   11979:                         }
                   11980: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11981: # hash populated for imported library file
                   11982:                         %metaentry = %currmetaentry;
                   11983:                         undef(%currmetaentry);
1.1068    www      11984:                         if ($importmode eq 'problem') {
1.1069    www      11985: # Import as problem/response
1.1068    www      11986:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11987:                         } elsif ($importmode eq 'part') {
                   11988: # Import as part(s)
1.1069    www      11989:                            $importedparts=1;
                   11990: # We need to get the original file and the imported file to get the part order correct
                   11991: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11992: # Load and inspect original file if we didn't do that already
                   11993:                            if ($#origfiletagids<0) {
                   11994:                                undef(%importedrespids);
                   11995:                                undef(%importedpartids);
                   11996:                                if ($origfile eq '') {
                   11997:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11998:                                    $origfile=&getfile($origfilelocation);
                   11999:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12000:                                }
1.1070    www      12001:                            }
                   12002: 
1.1069    www      12003: # Load and inspect imported file
                   12004:                            my $impfile=&getfile($location);
                   12005:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12006:                            if ($#impfilepartids>=0) {
                   12007: # This problem had parts
1.1070    www      12008:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12009:                            } else {
                   12010: # Importing by turning a single problem into a problem part
                   12011: # It gets the import-tags ID as part-ID
                   12012:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12013:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12014:                            }
1.1068    www      12015:                         } else {
                   12016: # Normal import
                   12017:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12018:                            if (defined($token->[2]->{'id'})) {
                   12019:                               $unikey.='_'.$token->[2]->{'id'};
                   12020:                            }
1.1067    www      12021:                         }
                   12022: 
1.339     albertel 12023: 			if ($depthcount<20) {
1.736     albertel 12024: 			    my $metadata = 
                   12025: 				&metadata($uri,'keys', $location,$unikey,
                   12026: 					  $depthcount+1);
                   12027: 			    foreach my $meta (split(',',$metadata)) {
                   12028: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12029: 				$metathesekeys{$meta}=1;
1.339     albertel 12030: 			    }
1.1068    www      12031: 			
                   12032:                         }
1.1067    www      12033: 		    } else {
                   12034: #
                   12035: # Not importing, some other kind of non-package, non-library start tag
                   12036: # 
                   12037:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12038:                         if (defined($token->[2]->{'id'})) {
                   12039:                             $unikey.='_'.$token->[2]->{'id'};
                   12040:                         }
1.339     albertel 12041: 			if (defined($token->[2]->{'name'})) { 
                   12042: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12043: 			}
                   12044: 			$metathesekeys{$unikey}=1;
1.736     albertel 12045: 			foreach my $param (@{$token->[3]}) {
                   12046: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12047: 				$token->[2]->{$param};
1.339     albertel 12048: 			}
                   12049: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12050: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12051: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12052: 		 # only ws inside the tag, and not in default, so use default
                   12053: 		 # as value
1.599     albertel 12054: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12055: 			} elsif ( $internaltext =~ /\S/ ) {
                   12056: 		  # something interesting inside the tag
                   12057: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12058: 			} else {
1.908     albertel 12059: 		  # no interesting values, don't set a default
1.339     albertel 12060: 			}
1.172     www      12061: # end of not-a-package not-a-library import
1.339     albertel 12062: 		    }
1.172     www      12063: # end of not-a-package start tag
1.339     albertel 12064: 		}
1.172     www      12065: # the next is the end of "start tag"
1.339     albertel 12066: 	    }
                   12067: 	}
1.483     albertel 12068: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12069: 	$extension = lc($extension);
                   12070: 	if ($extension eq 'htm') { $extension='html'; }
                   12071: 
1.737     albertel 12072: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12073: 	    #no specific packages #how's our extension
                   12074: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12075: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12076: 					 \%metathesekeys);
                   12077: 	}
1.883     albertel 12078: 
                   12079: 	if (!exists($metaentry{':packages'})
                   12080: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12081: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12082: 		#no specific packages well let's get default then
                   12083: 		if ($key!~/^default&/) { next; }
1.488     albertel 12084: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12085: 					     \%metathesekeys);
                   12086: 	    }
                   12087: 	}
1.338     www      12088: # are there custom rights to evaluate
1.599     albertel 12089: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12090: 
1.338     www      12091:     #
                   12092:     # Importing a rights file here
1.339     albertel 12093:     #
                   12094: 	    unless ($depthcount) {
1.599     albertel 12095: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12096: 		my $dir=$filename;
                   12097: 		$dir=~s|[^/]*$||;
                   12098: 		$location=&filelocation($dir,$location);
1.736     albertel 12099: 		my $rights_metadata =
                   12100: 		    &metadata($uri,'keys',$location,'_rights',
                   12101: 			      $depthcount+1);
                   12102: 		foreach my $rights (split(',',$rights_metadata)) {
                   12103: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12104: 		    $metathesekeys{$rights}=1;
1.339     albertel 12105: 		}
                   12106: 	    }
                   12107: 	}
1.737     albertel 12108: 	# uniqifiy package listing
                   12109: 	my %seen;
                   12110: 	my @uniq_packages =
                   12111: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12112: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12113: 
1.1172.2.99  raeburn  12114:         if (($importedresponses) || ($importedparts)) {
                   12115:             if ($importedparts) {
1.1070    www      12116: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12117:                 $metaentry{':partorder'}='';
                   12118:                 $metathesekeys{'partorder'}=1;
                   12119:             }
                   12120:             if ($importedresponses) {
                   12121: # We had imported responses and need to rebuild responseorder
                   12122:                 $metaentry{':responseorder'}='';
                   12123:                 $metathesekeys{'responseorder'}=1;
                   12124:             }
                   12125:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12126:                 my $origid = $origfiletagids[$index+1];
                   12127:                 if ($origfiletagids[$index] eq 'part') {
                   12128: # Original part, part of the problem
                   12129:                     if ($importedparts) {
                   12130:                         $metaentry{':partorder'}.=','.$origid;
                   12131:                     }
                   12132:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12133:                     if ($importedparts) {
                   12134: # We have imported parts at this position
                   12135:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12136:                     }
                   12137:                     if ($importedresponses) {
                   12138: # We have imported responses at this position
                   12139:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12140:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12141:                         }
                   12142:                     }
                   12143:                 } else {
                   12144: # Original response item, part of the problem
                   12145:                     if ($importedresponses) {
                   12146:                         $metaentry{':responseorder'}.=','.$origid;
                   12147:                     }
                   12148:                 }
                   12149:             }
                   12150:             if ($importedparts) {
                   12151:                 $metaentry{':partorder'}=~s/^\,//;
                   12152:             }
                   12153:             if ($importedresponses) {
                   12154:                 $metaentry{':responseorder'}=~s/^\,//;
                   12155:             }
1.1070    www      12156:         }
                   12157: 
1.737     albertel 12158: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12159: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12160: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12161: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12162: # this is the end of "was not already recently cached
1.71      www      12163:     }
1.599     albertel 12164:     return $metaentry{':'.$what};
1.261     albertel 12165: }
                   12166: 
1.488     albertel 12167: sub metadata_create_package_def {
1.483     albertel 12168:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12169:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12170:     if ($subp eq 'default') { next; }
                   12171:     
1.599     albertel 12172:     if (defined($metaentry{':packages'})) {
                   12173: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12174:     } else {
1.599     albertel 12175: 	$metaentry{':packages'}=$package;
1.483     albertel 12176:     }
                   12177:     my $value=$packagetab{$key};
                   12178:     my $unikey;
                   12179:     $unikey='parameter_0_'.$name;
1.599     albertel 12180:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12181:     $$metathesekeys{$unikey}=1;
1.599     albertel 12182:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12183: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12184:     }
1.599     albertel 12185:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12186: 	$metaentry{':'.$unikey}=
                   12187: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12188:     }
                   12189: }
                   12190: 
1.261     albertel 12191: sub metadata_generate_part0 {
                   12192:     my ($metadata,$metacache,$uri) = @_;
                   12193:     my %allnames;
1.737     albertel 12194:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12195: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12196: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12197: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12198: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12199: 	    $allnames{$name}=$part;
                   12200: 	  }
                   12201: 	}
                   12202:     }
                   12203:     foreach my $name (keys(%allnames)) {
                   12204:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12205:       my $key=":parameter_0_$name";
1.261     albertel 12206:       $$metacache{"$key.part"}='0';
                   12207:       $$metacache{"$key.name"}=$name;
1.428     albertel 12208:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12209: 					   $allnames{$name}.'_'.$name.
                   12210: 					   '.type'};
1.428     albertel 12211:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12212: 			     '.display'};
1.644     www      12213:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12214:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12215:       $$metacache{"$key.display"}=$olddis;
                   12216:     }
1.71      www      12217: }
                   12218: 
1.764     albertel 12219: # ------------------------------------------------------ Devalidate title cache
                   12220: 
                   12221: sub devalidate_title_cache {
                   12222:     my ($url)=@_;
                   12223:     if (!$env{'request.course.id'}) { return; }
                   12224:     my $symb=&symbread($url);
                   12225:     if (!$symb) { return; }
                   12226:     my $key=$env{'request.course.id'}."\0".$symb;
                   12227:     &devalidate_cache_new('title',$key);
                   12228: }
                   12229: 
1.1014    droeschl 12230: # ------------------------------------------------- Get the title of a course
                   12231: 
                   12232: sub current_course_title {
                   12233:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12234: }
1.301     www      12235: # ------------------------------------------------- Get the title of a resource
                   12236: 
                   12237: sub gettitle {
                   12238:     my $urlsymb=shift;
                   12239:     my $symb=&symbread($urlsymb);
1.534     albertel 12240:     if ($symb) {
1.620     albertel 12241: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12242: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12243: 	if (defined($cached)) { 
                   12244: 	    return $result;
                   12245: 	}
1.534     albertel 12246: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12247: 	my $title='';
1.907     albertel 12248: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12249: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12250: 	} else {
                   12251: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12252: 		    &GDBM_READER(),0640)) {
                   12253: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12254: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12255: 		untie(%bighash);
                   12256: 	    }
1.534     albertel 12257: 	}
                   12258: 	$title=~s/\&colon\;/\:/gs;
                   12259: 	if ($title) {
1.1159    www      12260: # Remember both $symb and $title for dynamic metadata
                   12261:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12262:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12263: # Cache this title and then return it
1.599     albertel 12264: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12265: 	}
                   12266: 	$urlsymb=$url;
                   12267:     }
                   12268:     my $title=&metadata($urlsymb,'title');
                   12269:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12270:     return $title;
1.301     www      12271: }
1.613     albertel 12272: 
1.614     albertel 12273: sub get_slot {
                   12274:     my ($which,$cnum,$cdom)=@_;
                   12275:     if (!$cnum || !$cdom) {
1.790     albertel 12276: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12277: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12278: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12279:     }
1.703     albertel 12280:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12281:     my %slotinfo;
                   12282:     if (exists($remembered{$key})) {
                   12283: 	$slotinfo{$which} = $remembered{$key};
                   12284:     } else {
                   12285: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12286: 	&Apache::lonhomework::showhash(%slotinfo);
                   12287: 	my ($tmp)=keys(%slotinfo);
                   12288: 	if ($tmp=~/^error:/) { return (); }
                   12289: 	$remembered{$key} = $slotinfo{$which};
                   12290:     }
1.616     albertel 12291:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12292: 	return %{$slotinfo{$which}};
                   12293:     }
                   12294:     return $slotinfo{$which};
1.614     albertel 12295: }
1.1150    raeburn  12296: 
                   12297: sub get_reservable_slots {
                   12298:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12299:     my $now = time;
                   12300:     my $reservable_info;
                   12301:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12302:     if (exists($remembered{$key})) {
                   12303:         $reservable_info = $remembered{$key};
                   12304:     } else {
                   12305:         my %resv;
                   12306:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12307:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12308:         $reservable_info = \%resv;
                   12309:         $remembered{$key} = $reservable_info;
                   12310:     }
                   12311:     return $reservable_info;
                   12312: }
                   12313: 
                   12314: sub get_course_slots {
                   12315:     my ($cnum,$cdom) = @_;
                   12316:     my $hashid=$cnum.':'.$cdom;
                   12317:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12318:     if (defined($cached)) {
                   12319:         if (ref($result) eq 'HASH') {
                   12320:             return %{$result};
                   12321:         }
                   12322:     } else {
                   12323:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12324:         my ($tmp) = keys(%slots);
                   12325:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12326:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12327:             return %slots;
                   12328:         }
                   12329:     }
                   12330:     return;
                   12331: }
                   12332: 
                   12333: sub devalidate_slots_cache {
                   12334:     my ($cnum,$cdom)=@_;
                   12335:     my $hashid=$cnum.':'.$cdom;
                   12336:     &devalidate_cache_new('allslots',$hashid);
                   12337: }
                   12338: 
1.1172.2.8  raeburn  12339: sub get_coursechange {
                   12340:     my ($cdom,$cnum) = @_;
                   12341:     if ($cdom eq '' || $cnum eq '') {
                   12342:         return unless ($env{'request.course.id'});
                   12343:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12344:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12345:     }
                   12346:     my $hashid=$cdom.'_'.$cnum;
                   12347:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12348:     if ((defined($cached)) && ($change ne '')) {
                   12349:         return $change;
                   12350:     } else {
                   12351:         my %crshash;
                   12352:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12353:         if ($crshash{'internal.contentchange'} eq '') {
                   12354:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12355:             if ($change eq '') {
                   12356:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12357:                 $change = $crshash{'internal.created'};
                   12358:             }
                   12359:         } else {
                   12360:             $change = $crshash{'internal.contentchange'};
                   12361:         }
                   12362:         my $cachetime = 600;
                   12363:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12364:     }
                   12365:     return $change;
                   12366: }
                   12367: 
                   12368: sub devalidate_coursechange_cache {
                   12369:     my ($cnum,$cdom)=@_;
                   12370:     my $hashid=$cnum.':'.$cdom;
                   12371:     &devalidate_cache_new('crschange',$hashid);
                   12372: }
                   12373: 
1.31      www      12374: # ------------------------------------------------- Update symbolic store links
                   12375: 
                   12376: sub symblist {
                   12377:     my ($mapname,%newhash)=@_;
1.438     www      12378:     $mapname=&deversion(&declutter($mapname));
1.31      www      12379:     my %hash;
1.620     albertel 12380:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12381:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12382:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12383: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12384: 		next if ($url eq 'last_known'
                   12385: 			 && $env{'form.no_update_last_known'});
                   12386: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12387: 						    $newhash{$url}->[1],
                   12388: 						    $newhash{$url}->[0]);
1.191     harris41 12389:             }
1.31      www      12390:             if (untie(%hash)) {
                   12391: 		return 'ok';
                   12392:             }
                   12393:         }
                   12394:     }
                   12395:     return 'error';
1.212     www      12396: }
                   12397: 
                   12398: # --------------------------------------------------------------- Verify a symb
                   12399: 
                   12400: sub symbverify {
1.1172.2.11  raeburn  12401:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12402:     my $thisfn=$thisurl;
1.439     www      12403:     $thisfn=&declutter($thisfn);
1.215     www      12404: # direct jump to resource in page or to a sequence - will construct own symbs
                   12405:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12406: # check URL part
1.409     www      12407:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12408: 
1.431     www      12409:     unless ($url eq $thisfn) { return 0; }
1.213     www      12410: 
1.216     www      12411:     $symb=&symbclean($symb);
1.510     www      12412:     $thisurl=&deversion($thisurl);
1.439     www      12413:     $thisfn=&deversion($thisfn);
1.213     www      12414: 
                   12415:     my %bighash;
                   12416:     my $okay=0;
1.431     www      12417: 
1.620     albertel 12418:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12419:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12420:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12421:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12422:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12423:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12424:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12425:             }
                   12426:         }
                   12427:         my $ids;
1.1172.2.118.  .5(raebu 12428:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12429:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12430:         } else {
                   12431:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12432:         }
1.1102    raeburn  12433:         unless ($ids) {
1.1172.2.13  raeburn  12434:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12435:             $ids=$bighash{$idkey};
1.216     www      12436:         }
                   12437:         if ($ids) {
                   12438: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12439:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12440:                 $symb =~ s/\?.+$//;
                   12441:             }
1.800     albertel 12442: 	    foreach my $id (split(/\,/,$ids)) {
                   12443: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12444:                if (
                   12445:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12446:    eq $symb) {
1.1172.2.11  raeburn  12447:                    if (ref($encstate)) {
                   12448:                        $$encstate = $bighash{'encrypted_'.$id};
                   12449:                    }
1.1172.2.13  raeburn  12450:                    if (($env{'request.role.adv'}) ||
                   12451:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12452:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12453:                        $okay=1;
                   12454:                        last;
                   12455:                    }
                   12456:                }
                   12457:            }
1.216     www      12458:         }
1.213     www      12459: 	untie(%bighash);
                   12460:     }
                   12461:     return $okay;
1.31      www      12462: }
                   12463: 
1.210     www      12464: # --------------------------------------------------------------- Clean-up symb
                   12465: 
                   12466: sub symbclean {
                   12467:     my $symb=shift;
1.568     albertel 12468:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12469: # remove version from map
                   12470:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12471: 
1.210     www      12472: # remove version from URL
                   12473:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12474: 
1.507     www      12475: # remove wrapper
                   12476: 
1.510     www      12477:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12478:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12479:     return $symb;
1.409     www      12480: }
                   12481: 
                   12482: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12483: 
                   12484: sub encode_symb {
                   12485:     my ($map,$resid,$url)=@_;
                   12486:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12487: }
1.409     www      12488: 
                   12489: sub decode_symb {
1.568     albertel 12490:     my $symb=shift;
                   12491:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12492:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12493:     return (&fixversion($map),$resid,&fixversion($url));
                   12494: }
                   12495: 
                   12496: sub fixversion {
                   12497:     my $fn=shift;
1.609     banghart 12498:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12499:     my %bighash;
                   12500:     my $uri=&clutter($fn);
1.620     albertel 12501:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12502: # is this cached?
1.599     albertel 12503:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12504:     if (defined($cached)) { return $result; }
                   12505: # unfortunately not cached, or expired
1.620     albertel 12506:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12507: 	    &GDBM_READER(),0640)) {
                   12508:  	if ($bighash{'version_'.$uri}) {
                   12509:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12510:  	    unless (($version eq 'mostrecent') || 
                   12511: 		    ($version==&getversion($uri))) {
1.440     www      12512:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12513:  	    }
                   12514:  	}
                   12515:  	untie %bighash;
1.413     www      12516:     }
1.599     albertel 12517:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12518: }
                   12519: 
                   12520: sub deversion {
                   12521:     my $url=shift;
                   12522:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12523:     return $url;
1.210     www      12524: }
                   12525: 
1.31      www      12526: # ------------------------------------------------------ Return symb list entry
                   12527: 
                   12528: sub symbread {
1.1172.2.118.  .8(raebu 12529:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
                   12530:20):         $nocache,$noenccheck)=@_;
1.1172.2.54  raeburn  12531:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .8(raebu 12532:20):     if (defined($env{$cache_str}) && !$nocache) {
                   12533:20):         unless (ref($possibles) eq 'HASH') {
                   12534:20):             if ($ignorecachednull) {
                   12535:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12536:20):             } else {
                   12537:20):                 return $env{$cache_str};
                   12538:20):             }
1.1172.2.66  raeburn  12539:         }
                   12540:     }
1.242     www      12541: # no filename provided? try from environment
1.1172.2.54  raeburn  12542:     unless ($thisfn) {
1.620     albertel 12543:         if ($env{'request.symb'}) {
1.1172.2.118.  .8(raebu 12544:20):             if ($nocache) {
                   12545:20):                 return &symbclean($env{'request.symb'});
                   12546:20):             } else {
                   12547:20):                 return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12548:20):             }
1.1172.2.13  raeburn  12549:         }
                   12550:         $thisfn=$env{'request.filename'};
1.44      www      12551:     }
1.569     albertel 12552:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12553: # is that filename actually a symb? Verify, clean, and return
                   12554:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12555: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .8(raebu 12556:20):             if ($nocache) {
                   12557:20):                 return &symbclean($thisfn);
                   12558:20):             } else {
                   12559:20): 	        return $env{$cache_str}=&symbclean($thisfn);
                   12560:20):             }
1.539     albertel 12561: 	}
1.242     www      12562:     }
1.44      www      12563:     $thisfn=declutter($thisfn);
1.31      www      12564:     my %hash;
1.37      www      12565:     my %bighash;
                   12566:     my $syval='';
1.620     albertel 12567:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12568:         my $targetfn = $thisfn;
1.609     banghart 12569:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12570:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12571:         }
1.687     albertel 12572: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12573: 	    $targetfn=$1;
                   12574: 	}
1.1172.2.118.  .8(raebu 12575:20):         unless ($nocache) {
                   12576:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12577:20):                           &GDBM_READER(),0640)) {
                   12578:20): 	        $syval=$hash{$targetfn};
                   12579:20):                 untie(%hash);
                   12580:20):             }
                   12581:20):             if ($syval) {
                   12582:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$nocache,$noenccheck);
                   12583:20):                 if (@blockers) {
                   12584:20):                     $syval='';
                   12585:20):                 }
                   12586:20):             }
1.37      www      12587:         }
                   12588: # ---------------------------------------------------------- There was an entry
                   12589:         if ($syval) {
1.601     albertel 12590: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12591: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12592: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12593: 		    #return $env{$cache_str}='';
1.601     albertel 12594: 		#}    
                   12595: 		#$syval.=$1;
                   12596: 	    #}
1.37      www      12597:         } else {
                   12598: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12599:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12600:                             &GDBM_READER(),0640)) {
1.37      www      12601: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12602:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12603:               unless ($ids) { 
                   12604:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12605:               }
                   12606:               unless ($ids) {
                   12607: # alias?
                   12608: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12609:               }
1.37      www      12610:               if ($ids) {
                   12611: # ------------------------------------------------------------------- Has ID(s)
                   12612:                  my @possibilities=split(/\,/,$ids);
1.39      www      12613:                  if ($#possibilities==0) {
                   12614: # ----------------------------------------------- There is only one possibility
1.37      www      12615: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12616: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12617: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12618:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12619:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12620:20):                              $possibles->{$syval} = 1;
                   12621:20):                          }
1.1172.2.66  raeburn  12622:                      }
                   12623:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12624:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12625:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12626:20):                              if (@blockers) {
                   12627:20):                                  $syval = '';
                   12628:20):                                  untie(%bighash);
                   12629:20):                                  return '' if ($nocache);
                   12630:20):                                  return $env{$cache_str}='';
                   12631:20):                              }
1.1172.2.66  raeburn  12632:                          }
                   12633:                      }
                   12634:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12635: # ------------------------------------------ There is more than one possibility
                   12636:                      my $realpossible=0;
1.800     albertel 12637:                      foreach my $id (@possibilities) {
                   12638: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12639:                          my $canaccess;
                   12640:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12641:                              $canaccess = 1;
                   12642:                          } else {
                   12643:                              $canaccess = &allowed('bre',$file);
                   12644:                          }
                   12645:                          if ($canaccess) {
                   12646:          		     my ($mapid,$resid)=split(/\./,$id);
                   12647:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12648:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12649:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12650:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12651:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12652:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12653:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12654:20):                                      if (@blockers > 0) {
                   12655:20):                                          $syval = '';
                   12656:20):                                      } else {
1.1172.2.66  raeburn  12657:                                          $syval = $poss_syval;
                   12658:                                          $realpossible++;
                   12659:                                      }
                   12660:                                  } else {
                   12661:                                      $syval = $poss_syval;
                   12662:                                      $realpossible++;
                   12663:                                  }
1.1172.2.118.  .8(raebu 12664:20):                                  if ($syval) {
                   12665:20):                                      if (ref($possibles) eq 'HASH') {
                   12666:20):                                          $possibles->{$syval} = 1;
                   12667:20):                                      }
                   12668:20):                                  }
1.1172.2.66  raeburn  12669:                              }
1.39      www      12670: 			 }
1.191     harris41 12671:                      }
1.39      www      12672: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12673:                  } else {
                   12674:                      $syval='';
1.37      www      12675:                  }
                   12676: 	      }
1.1172.2.66  raeburn  12677:               untie(%bighash);
1.481     raeburn  12678:            }
1.31      www      12679:         }
1.62      www      12680:         if ($syval) {
1.1172.2.118.  .8(raebu 12681:20):             if ($nocache) {
                   12682:20):                 return $syval;
                   12683:20):             } else {
                   12684:20): 	        return $env{$cache_str}=$syval;
                   12685:20):             }
1.62      www      12686:         }
1.31      www      12687:     }
1.949     raeburn  12688:     &appenv({'request.ambiguous' => $thisfn});
1.1172.2.118.  .8(raebu 12689:20):     return '' if ($nocache);
1.620     albertel 12690:     return $env{$cache_str}='';
1.31      www      12691: }
                   12692: 
                   12693: # ---------------------------------------------------------- Return random seed
                   12694: 
1.32      www      12695: sub numval {
                   12696:     my $txt=shift;
                   12697:     $txt=~tr/A-J/0-9/;
                   12698:     $txt=~tr/a-j/0-9/;
                   12699:     $txt=~tr/K-T/0-9/;
                   12700:     $txt=~tr/k-t/0-9/;
                   12701:     $txt=~tr/U-Z/0-5/;
                   12702:     $txt=~tr/u-z/0-5/;
                   12703:     $txt=~s/\D//g;
1.564     albertel 12704:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12705:     return int($txt);
1.368     albertel 12706: }
                   12707: 
1.484     albertel 12708: sub numval2 {
                   12709:     my $txt=shift;
                   12710:     $txt=~tr/A-J/0-9/;
                   12711:     $txt=~tr/a-j/0-9/;
                   12712:     $txt=~tr/K-T/0-9/;
                   12713:     $txt=~tr/k-t/0-9/;
                   12714:     $txt=~tr/U-Z/0-5/;
                   12715:     $txt=~tr/u-z/0-5/;
                   12716:     $txt=~s/\D//g;
                   12717:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12718:     my $total;
                   12719:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12720:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12721:     return int($total);
                   12722: }
                   12723: 
1.575     albertel 12724: sub numval3 {
                   12725:     use integer;
                   12726:     my $txt=shift;
                   12727:     $txt=~tr/A-J/0-9/;
                   12728:     $txt=~tr/a-j/0-9/;
                   12729:     $txt=~tr/K-T/0-9/;
                   12730:     $txt=~tr/k-t/0-9/;
                   12731:     $txt=~tr/U-Z/0-5/;
                   12732:     $txt=~tr/u-z/0-5/;
                   12733:     $txt=~s/\D//g;
                   12734:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12735:     my $total;
                   12736:     foreach my $val (@txts) { $total+=$val; }
                   12737:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12738:     return $total;
                   12739: }
                   12740: 
1.675     albertel 12741: sub digest {
                   12742:     my ($data)=@_;
                   12743:     my $digest=&Digest::MD5::md5($data);
                   12744:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12745:     my ($e,$f);
                   12746:     {
                   12747:         use integer;
                   12748:         $e=($a+$b);
                   12749:         $f=($c+$d);
                   12750:         if ($_64bit) {
                   12751:             $e=(($e<<32)>>32);
                   12752:             $f=(($f<<32)>>32);
                   12753:         }
                   12754:     }
                   12755:     if (wantarray) {
                   12756: 	return ($e,$f);
                   12757:     } else {
                   12758: 	my $g;
                   12759: 	{
                   12760: 	    use integer;
                   12761: 	    $g=($e+$f);
                   12762: 	    if ($_64bit) {
                   12763: 		$g=(($g<<32)>>32);
                   12764: 	    }
                   12765: 	}
                   12766: 	return $g;
                   12767:     }
                   12768: }
                   12769: 
1.368     albertel 12770: sub latest_rnd_algorithm_id {
1.675     albertel 12771:     return '64bit5';
1.366     albertel 12772: }
1.32      www      12773: 
1.503     albertel 12774: sub get_rand_alg {
                   12775:     my ($courseid)=@_;
1.790     albertel 12776:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12777:     if ($courseid) {
1.620     albertel 12778: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12779:     }
                   12780:     return &latest_rnd_algorithm_id();
                   12781: }
                   12782: 
1.562     albertel 12783: sub validCODE {
                   12784:     my ($CODE)=@_;
                   12785:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12786:     return 0;
                   12787: }
                   12788: 
1.491     albertel 12789: sub getCODE {
1.620     albertel 12790:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12791:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12792: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12793: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12794: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12795:     }
                   12796:     return undef;
                   12797: }
1.1133    foxr     12798: #
                   12799: #  Determines the random seed for a specific context:
                   12800: #
                   12801: # parameters:
                   12802: #   symb      - in course context the symb for the seed.
                   12803: #   course_id - The course id of the form domain_coursenum.
                   12804: #   domain    - Domain for the user.
                   12805: #   course    - Course for the user.
                   12806: #   cenv      - environment of the course.
                   12807: #
                   12808: # NOTE:
                   12809: #   All parameters are picked out of the environment if missing
                   12810: #   or not defined.
                   12811: #   If a symb cannot be determined the current time is used instead.
                   12812: #
                   12813: #  For a given well defined symb, courside, domain, username,
                   12814: #  and course environment, the seed is reproducible.
                   12815: #
1.31      www      12816: sub rndseed {
1.1133    foxr     12817:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12818:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12819:     if (!defined($symb)) {
1.366     albertel 12820: 	unless ($symb=$wsymb) { return time; }
                   12821:     }
1.1146    foxr     12822:     if (!defined $courseid) { 
                   12823: 	$courseid=$wcourseid; 
                   12824:     }
                   12825:     if (!defined $domain) { $domain=$wdomain; }
                   12826:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12827: 
                   12828:     my $which;
                   12829:     if (defined($cenv->{'rndseed'})) {
                   12830: 	$which = $cenv->{'rndseed'};
                   12831:     } else {
                   12832: 	$which =&get_rand_alg($courseid);
                   12833:     }
1.491     albertel 12834:     if (defined(&getCODE())) {
1.675     albertel 12835: 	if ($which eq '64bit5') {
                   12836: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12837: 	} elsif ($which eq '64bit4') {
1.575     albertel 12838: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12839: 	} else {
                   12840: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12841: 	}
1.675     albertel 12842:     } elsif ($which eq '64bit5') {
                   12843: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12844:     } elsif ($which eq '64bit4') {
                   12845: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12846:     } elsif ($which eq '64bit3') {
                   12847: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12848:     } elsif ($which eq '64bit2') {
                   12849: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12850:     } elsif ($which eq '64bit') {
                   12851: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12852:     }
                   12853:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12854: }
                   12855: 
                   12856: sub rndseed_32bit {
                   12857:     my ($symb,$courseid,$domain,$username)=@_;
                   12858:     {
                   12859: 	use integer;
                   12860: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12861: 	my $symbseed=numval($symb) << 22;
                   12862: 	my $namechck=unpack("%32C*",$username) << 17;
                   12863: 	my $nameseed=numval($username) << 12;
                   12864: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12865: 	my $courseseed=unpack("%32C*",$courseid);
                   12866: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12867: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12868: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12869: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12870: 	return $num;
                   12871:     }
                   12872: }
                   12873: 
                   12874: sub rndseed_64bit {
                   12875:     my ($symb,$courseid,$domain,$username)=@_;
                   12876:     {
                   12877: 	use integer;
                   12878: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12879: 	my $symbseed=numval($symb) << 10;
                   12880: 	my $namechck=unpack("%32S*",$username);
                   12881: 	
                   12882: 	my $nameseed=numval($username) << 21;
                   12883: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12884: 	my $courseseed=unpack("%32S*",$courseid);
                   12885: 	
                   12886: 	my $num1=$symbchck+$symbseed+$namechck;
                   12887: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12889: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12890: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12891: 	return "$num1,$num2";
1.155     albertel 12892:     }
1.366     albertel 12893: }
                   12894: 
1.443     albertel 12895: sub rndseed_64bit2 {
                   12896:     my ($symb,$courseid,$domain,$username)=@_;
                   12897:     {
                   12898: 	use integer;
                   12899: 	# strings need to be an even # of cahracters long, it it is odd the
                   12900:         # last characters gets thrown away
                   12901: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12902: 	my $symbseed=numval($symb) << 10;
                   12903: 	my $namechck=unpack("%32S*",$username.' ');
                   12904: 	
                   12905: 	my $nameseed=numval($username) << 21;
1.501     albertel 12906: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12907: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12908: 	
                   12909: 	my $num1=$symbchck+$symbseed+$namechck;
                   12910: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12911: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12912: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12913: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12914: 	return "$num1,$num2";
                   12915:     }
                   12916: }
                   12917: 
                   12918: sub rndseed_64bit3 {
                   12919:     my ($symb,$courseid,$domain,$username)=@_;
                   12920:     {
                   12921: 	use integer;
                   12922: 	# strings need to be an even # of cahracters long, it it is odd the
                   12923:         # last characters gets thrown away
                   12924: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12925: 	my $symbseed=numval2($symb) << 10;
                   12926: 	my $namechck=unpack("%32S*",$username.' ');
                   12927: 	
                   12928: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12929: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12930: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12931: 	
                   12932: 	my $num1=$symbchck+$symbseed+$namechck;
                   12933: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12934: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12935: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12936: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12937: 	
1.503     albertel 12938: 	return "$num1:$num2";
1.443     albertel 12939:     }
                   12940: }
                   12941: 
1.575     albertel 12942: sub rndseed_64bit4 {
                   12943:     my ($symb,$courseid,$domain,$username)=@_;
                   12944:     {
                   12945: 	use integer;
                   12946: 	# strings need to be an even # of cahracters long, it it is odd the
                   12947:         # last characters gets thrown away
                   12948: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12949: 	my $symbseed=numval3($symb) << 10;
                   12950: 	my $namechck=unpack("%32S*",$username.' ');
                   12951: 	
                   12952: 	my $nameseed=numval3($username) << 21;
                   12953: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12954: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12955: 	
                   12956: 	my $num1=$symbchck+$symbseed+$namechck;
                   12957: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12958: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12959: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12960: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12961: 	
1.575     albertel 12962: 	return "$num1:$num2";
                   12963:     }
                   12964: }
                   12965: 
1.675     albertel 12966: sub rndseed_64bit5 {
                   12967:     my ($symb,$courseid,$domain,$username)=@_;
                   12968:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12969:     return "$num1:$num2";
                   12970: }
                   12971: 
1.366     albertel 12972: sub rndseed_CODE_64bit {
                   12973:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12974:     {
1.366     albertel 12975: 	use integer;
1.443     albertel 12976: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12977: 	my $symbseed=numval2($symb);
1.491     albertel 12978: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12979: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12980: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12981: 	my $num1=$symbseed+$CODEchck;
                   12982: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12983: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12984: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12985: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12986: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12987: 	return "$num1:$num2";
1.366     albertel 12988:     }
                   12989: }
                   12990: 
1.575     albertel 12991: sub rndseed_CODE_64bit4 {
                   12992:     my ($symb,$courseid,$domain,$username)=@_;
                   12993:     {
                   12994: 	use integer;
                   12995: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12996: 	my $symbseed=numval3($symb);
                   12997: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12998: 	my $CODEseed=numval3(&getCODE());
                   12999: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13000: 	my $num1=$symbseed+$CODEchck;
                   13001: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13002: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13003: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13004: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13005: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13006: 	return "$num1:$num2";
                   13007:     }
                   13008: }
                   13009: 
1.675     albertel 13010: sub rndseed_CODE_64bit5 {
                   13011:     my ($symb,$courseid,$domain,$username)=@_;
                   13012:     my $code = &getCODE();
                   13013:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13014:     return "$num1:$num2";
                   13015: }
                   13016: 
1.366     albertel 13017: sub setup_random_from_rndseed {
                   13018:     my ($rndseed)=@_;
1.503     albertel 13019:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13020: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13021:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13022:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13023:         } else {
                   13024:             &Math::Random::random_set_seed($num1,$num2);
                   13025:         }
1.366     albertel 13026:     } else {
                   13027: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13028:     }
1.36      albertel 13029: }
                   13030: 
1.474     albertel 13031: sub latest_receipt_algorithm_id {
1.835     albertel 13032:     return 'receipt3';
1.474     albertel 13033: }
                   13034: 
1.480     www      13035: sub recunique {
                   13036:     my $fucourseid=shift;
                   13037:     my $unique;
1.835     albertel 13038:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13039: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13040: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13041:     } else {
                   13042: 	$unique=$perlvar{'lonReceipt'};
                   13043:     }
                   13044:     return unpack("%32C*",$unique);
                   13045: }
                   13046: 
                   13047: sub recprefix {
                   13048:     my $fucourseid=shift;
                   13049:     my $prefix;
1.835     albertel 13050:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13051: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13052: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13053:     } else {
                   13054: 	$prefix=$perlvar{'lonHostID'};
                   13055:     }
                   13056:     return unpack("%32C*",$prefix);
                   13057: }
                   13058: 
1.76      www      13059: sub ireceipt {
1.474     albertel 13060:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13061: 
                   13062:     my $return =&recprefix($fucourseid).'-';
                   13063: 
                   13064:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13065: 	$env{'request.state'} eq 'construct') {
                   13066: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13067: 	return $return;
                   13068:     }
                   13069: 
1.76      www      13070:     my $cuname=unpack("%32C*",$funame);
                   13071:     my $cudom=unpack("%32C*",$fudom);
                   13072:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13073:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13074:     my $cunique=&recunique($fucourseid);
1.474     albertel 13075:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13076:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13077: 
1.790     albertel 13078: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13079: 			       
                   13080: 	$return.= ($cunique%$cuname+
                   13081: 		   $cunique%$cudom+
                   13082: 		   $cusymb%$cuname+
                   13083: 		   $cusymb%$cudom+
                   13084: 		   $cucourseid%$cuname+
                   13085: 		   $cucourseid%$cudom+
                   13086: 		   $cpart%$cuname+
                   13087: 		   $cpart%$cudom);
                   13088:     } else {
                   13089: 	$return.= ($cunique%$cuname+
                   13090: 		   $cunique%$cudom+
                   13091: 		   $cusymb%$cuname+
                   13092: 		   $cusymb%$cudom+
                   13093: 		   $cucourseid%$cuname+
                   13094: 		   $cucourseid%$cudom);
                   13095:     }
                   13096:     return $return;
1.76      www      13097: }
                   13098: 
                   13099: sub receipt {
1.474     albertel 13100:     my ($part)=@_;
1.790     albertel 13101:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13102:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13103: }
1.260     ng       13104: 
1.790     albertel 13105: sub whichuser {
                   13106:     my ($passedsymb)=@_;
                   13107:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13108:     if (defined($env{'form.grade_symb'})) {
                   13109: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13110: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13111: 	if (!$allowed &&
                   13112: 	    exists($env{'request.course.sec'}) &&
                   13113: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13114: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13115: 			      '/'.$env{'request.course.sec'});
                   13116: 	}
                   13117: 	if ($allowed) {
                   13118: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13119: 	    $courseid=$tmp_courseid;
                   13120: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13121: 	    ($name)=&get_env_multiple('form.grade_username');
                   13122: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13123: 	}
                   13124:     }
                   13125:     if (!$passedsymb) {
                   13126: 	$symb=&symbread();
                   13127:     } else {
                   13128: 	$symb=$passedsymb;
                   13129:     }
                   13130:     $courseid=$env{'request.course.id'};
                   13131:     $domain=$env{'user.domain'};
                   13132:     $name=$env{'user.name'};
                   13133:     if ($name eq 'public' && $domain eq 'public') {
                   13134: 	if (!defined($env{'form.username'})) {
                   13135: 	    $env{'form.username'}.=time.rand(10000000);
                   13136: 	}
                   13137: 	$name.=$env{'form.username'};
                   13138:     }
                   13139:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13140: 
                   13141: }
                   13142: 
1.36      albertel 13143: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13144: # returns either the contents of the file or 
                   13145: # -1 if the file doesn't exist
1.481     raeburn  13146: #
                   13147: # if the target is a file that was uploaded via DOCS, 
                   13148: # a check will be made to see if a current copy exists on the local server,
                   13149: # if it does this will be served, otherwise a copy will be retrieved from
                   13150: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13151: # the local server.   
1.472     albertel 13152: 
1.36      albertel 13153: sub getfile {
1.538     albertel 13154:     my ($file) = @_;
1.609     banghart 13155:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13156:     &repcopy($file);
                   13157:     return &readfile($file);
                   13158: }
                   13159: 
                   13160: sub repcopy_userfile {
                   13161:     my ($file)=@_;
1.1142    raeburn  13162:     my $londocroot = $perlvar{'lonDocRoot'};
                   13163:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13164:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13165:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13166: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13167:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13168:     if (-e "$file") {
1.828     www      13169: # we already have a local copy, check it out
1.538     albertel 13170: 	my @fileinfo = stat($file);
1.828     www      13171: 	my $rtncode;
                   13172: 	my $info;
1.538     albertel 13173: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13174: 	if ($lwpresp ne 'ok') {
1.828     www      13175: # there is no such file anymore, even though we had a local copy
1.482     albertel 13176: 	    if ($rtncode eq '404') {
1.538     albertel 13177: 		unlink($file);
1.482     albertel 13178: 	    }
                   13179: 	    return -1;
                   13180: 	}
                   13181: 	if ($info < $fileinfo[9]) {
1.828     www      13182: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13183: 	    return 'ok';
1.828     www      13184: 	} else {
                   13185: # the file is outdated, get rid of it
                   13186: 	    unlink($file);
1.482     albertel 13187: 	}
1.828     www      13188:     }
                   13189: # one way or the other, at this point, we don't have the file
                   13190: # construct the correct path for the file
                   13191:     my @parts = ($cdom,$cnum); 
                   13192:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13193: 	push @parts, split(/\//,$1);
                   13194:     }
                   13195:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13196:     foreach my $part (@parts) {
                   13197: 	$path .= '/'.$part;
                   13198: 	if (!-e $path) {
                   13199: 	    mkdir($path,0770);
1.482     albertel 13200: 	}
                   13201:     }
1.828     www      13202: # now the path exists for sure
                   13203: # get a user agent
                   13204:     my $ua=new LWP::UserAgent;
                   13205:     my $transferfile=$file.'.in.transfer';
                   13206: # FIXME: this should flock
                   13207:     if (-e $transferfile) { return 'ok'; }
                   13208:     my $request;
                   13209:     $uri=~s/^\///;
1.980     raeburn  13210:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13211:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13212:     my $protocol = $protocol{$homeserver};
                   13213:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13214:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13215:     my $response=$ua->request($request,$transferfile);
                   13216: # did it work?
                   13217:     if ($response->is_error()) {
                   13218: 	unlink($transferfile);
                   13219: 	&logthis("Userfile repcopy failed for $uri");
                   13220: 	return -1;
                   13221:     }
                   13222: # worked, rename the transfer file
                   13223:     rename($transferfile,$file);
1.607     raeburn  13224:     return 'ok';
1.481     raeburn  13225: }
                   13226: 
1.517     albertel 13227: sub tokenwrapper {
                   13228:     my $uri=shift;
1.980     raeburn  13229:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13230:     $uri=~s|^/||;
1.620     albertel 13231:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13232:     my $token=$1;
1.552     albertel 13233:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13234:     if ($udom && $uname && $file) {
                   13235: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13236:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13237:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13238:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13239:         my $protocol = $protocol{$homeserver};
                   13240:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13241:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13242:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13243:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13244:     } else {
                   13245:         return '/adm/notfound.html';
                   13246:     }
                   13247: }
                   13248: 
1.828     www      13249: # call with reqtype HEAD: get last modification time
                   13250: # call with reqtype GET: get the file contents
                   13251: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13252: #
1.481     raeburn  13253: sub getuploaded {
                   13254:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13255:     $uri=~s/^\///;
1.980     raeburn  13256:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13257:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13258:     my $protocol = $protocol{$homeserver};
                   13259:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13260:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13261:     my $ua=new LWP::UserAgent;
                   13262:     my $request=new HTTP::Request($reqtype,$uri);
                   13263:     my $response=$ua->request($request);
                   13264:     $$rtncode = $response->code;
1.482     albertel 13265:     if (! $response->is_success()) {
                   13266: 	return 'failed';
                   13267:     }      
                   13268:     if ($reqtype eq 'HEAD') {
1.486     www      13269: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13270:     } elsif ($reqtype eq 'GET') {
                   13271: 	$$info = $response->content;
1.472     albertel 13272:     }
1.482     albertel 13273:     return 'ok';
1.36      albertel 13274: }
                   13275: 
1.481     raeburn  13276: sub readfile {
                   13277:     my $file = shift;
                   13278:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13279:     my $fh;
1.1172.2.96  raeburn  13280:     open($fh,"<",$file);
1.481     raeburn  13281:     my $a='';
1.800     albertel 13282:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13283:     return $a;
                   13284: }
                   13285: 
1.36      albertel 13286: sub filelocation {
1.590     banghart 13287:     my ($dir,$file) = @_;
                   13288:     my $location;
                   13289:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13290: 
                   13291:     if ($file =~ m-^/adm/-) {
                   13292: 	$file=~s-^/adm/wrapper/-/-;
                   13293: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13294:     }
1.882     albertel 13295: 
1.1139    www      13296:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13297:         $location = $file;
1.609     banghart 13298:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13299:         my ($udom,$uname,$filename)=
1.811     albertel 13300:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13301:         my $home=&homeserver($uname,$udom);
                   13302:         my $is_me=0;
                   13303:         my @ids=&current_machine_ids();
                   13304:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13305:         if ($is_me) {
1.1117    foxr     13306:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13307:         } else {
                   13308:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13309:   	      $udom.'/'.$uname.'/'.$filename;
                   13310:         }
1.882     albertel 13311:     } elsif ($file =~ m-^/adm/-) {
                   13312: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13313:     } else {
                   13314:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13315:         $file=~s:^/(res|priv)/:/:;
                   13316:         my $space=$1;
1.590     banghart 13317:         if ( !( $file =~ m:^/:) ) {
                   13318:             $location = $dir. '/'.$file;
                   13319:         } else {
1.1142    raeburn  13320:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13321:         }
1.59      albertel 13322:     }
1.590     banghart 13323:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13324:     while ($location=~m{/\.\./}) {
                   13325: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13326: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13327: 	} else {
                   13328: 	    $location=~ s{/\.\./}{/}g;
                   13329: 	}
                   13330:     } #remove dir/..
1.590     banghart 13331:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13332:     return $location;
1.46      www      13333: }
1.36      albertel 13334: 
1.46      www      13335: sub hreflocation {
                   13336:     my ($dir,$file)=@_;
1.980     raeburn  13337:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13338: 	$file=filelocation($dir,$file);
1.700     albertel 13339:     } elsif ($file=~m-^/adm/-) {
                   13340: 	$file=~s-^/adm/wrapper/-/-;
                   13341: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13342:     }
                   13343:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13344: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13345:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13346: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13347: 	        {/uploaded/$1/$2/}x;
1.46      www      13348:     }
1.913     albertel 13349:     if ($file=~ m{^/userfiles/}) {
                   13350: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13351:     }
1.462     albertel 13352:     return $file;
1.465     albertel 13353: }
                   13354: 
1.1139    www      13355: 
                   13356: 
                   13357: 
                   13358: 
1.465     albertel 13359: sub current_machine_domains {
1.853     albertel 13360:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13361: }
                   13362: 
                   13363: sub machine_domains {
                   13364:     my ($hostname) = @_;
1.465     albertel 13365:     my @domains;
1.838     albertel 13366:     my %hostname = &all_hostnames();
1.465     albertel 13367:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13368: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13369: 	if ($hostname eq $name) {
1.844     albertel 13370: 	    push(@domains,&host_domain($id));
1.465     albertel 13371: 	}
                   13372:     }
                   13373:     return @domains;
                   13374: }
                   13375: 
                   13376: sub current_machine_ids {
1.853     albertel 13377:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13378: }
                   13379: 
                   13380: sub machine_ids {
                   13381:     my ($hostname) = @_;
                   13382:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13383:     my @ids;
1.888     albertel 13384:     my %name_to_host = &all_names();
1.889     albertel 13385:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13386: 	return @{ $name_to_host{$hostname} };
                   13387:     }
                   13388:     return;
1.31      www      13389: }
                   13390: 
1.824     raeburn  13391: sub additional_machine_domains {
                   13392:     my @domains;
1.1172.2.96  raeburn  13393:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13394:     while( my $line = <$fh>) {
                   13395:         $line =~ s/\s//g;
                   13396:         push(@domains,$line);
                   13397:     }
                   13398:     return @domains;
                   13399: }
                   13400: 
                   13401: sub default_login_domain {
                   13402:     my $domain = $perlvar{'lonDefDomain'};
                   13403:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13404:     foreach my $posdom (&current_machine_domains(),
                   13405:                         &additional_machine_domains()) {
                   13406:         if (lc($posdom) eq lc($testdomain)) {
                   13407:             $domain=$posdom;
                   13408:             last;
                   13409:         }
                   13410:     }
                   13411:     return $domain;
                   13412: }
                   13413: 
1.1172.2.106  raeburn  13414: sub shared_institution {
                   13415:     my ($dom) = @_;
                   13416:     my $same_intdom;
                   13417:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13418:     if ($hostintdom ne '') {
                   13419:         my %iphost = &get_iphost();
                   13420:         my $primary_id = &domain($dom,'primary');
                   13421:         my $primary_ip = &get_host_ip($primary_id);
                   13422:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13423:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13424:                 my $intdom = &internet_dom($id);
                   13425:                 if ($intdom eq $hostintdom) {
                   13426:                     $same_intdom = 1;
                   13427:                     last;
                   13428:                 }
                   13429:             }
                   13430:         }
                   13431:     }
                   13432:     return $same_intdom;
                   13433: }
                   13434: 
1.1172.2.118.  .3(raebu 13435:20): sub uses_sts {
                   13436:20):     my ($ignore_cache) = @_;
                   13437:20):     my $lonhost = $perlvar{'lonHostID'};
                   13438:20):     my $hostname = &hostname($lonhost);
                   13439:20):     my $sts_on;
                   13440:20):     if ($protocol{$lonhost} eq 'https') {
                   13441:20):         my $cachetime = 12*3600;
                   13442:20):         if (!$ignore_cache) {
                   13443:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13444:20):             if (defined($cached)) {
                   13445:20):                 return $sts_on;
                   13446:20):             }
                   13447:20):         }
          .4(raebu 13448:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13449:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13450:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13451:20):         my $response=$ua->request($request);
          .3(raebu 13452:20):         if ($response->is_success) {
                   13453:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13454:20):             if ($has_sts eq '') {
                   13455:20):                 $sts_on = 0;
                   13456:20):             } else {
                   13457:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13458:20):                     my $maxage = $1;
                   13459:20):                     if ($maxage) {
                   13460:20):                         $sts_on = 1;
                   13461:20):                     } else {
                   13462:20):                         $sts_on = 0;
                   13463:20):                     }
                   13464:20):                 } else {
                   13465:20):                     $sts_on = 0;
                   13466:20):                 }
                   13467:20):             }
                   13468:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13469:20):         }
                   13470:20):     }
                   13471:20):     return;
                   13472:20): }
                   13473:20): 
1.31      www      13474: # ------------------------------------------------------------- Declutters URLs
                   13475: 
                   13476: sub declutter {
                   13477:     my $thisfn=shift;
1.569     albertel 13478:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13479:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13480:         $thisfn=~s{^/home/httpd/html}{};
                   13481:     }
1.31      www      13482:     $thisfn=~s/^\///;
1.697     albertel 13483:     $thisfn=~s|^adm/wrapper/||;
                   13484:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13485:     $thisfn=~s/^res\///;
1.1172    bisitz   13486:     $thisfn=~s/^priv\///;
1.1032    raeburn  13487:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13488:         $thisfn=~s/\?.+$//;
                   13489:     }
1.268     www      13490:     return $thisfn;
                   13491: }
                   13492: 
                   13493: # ------------------------------------------------------------- Clutter up URLs
                   13494: 
                   13495: sub clutter {
                   13496:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13497:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13498: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13499:        $thisfn='/res'.$thisfn; 
                   13500:     }
1.1031    raeburn  13501:     if ($thisfn !~m|^/adm|) {
                   13502: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13503: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13504: 	} else {
                   13505: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13506: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13507: 	    if ($embstyle eq 'ssi'
                   13508: 		|| ($embstyle eq 'hdn')
                   13509: 		|| ($embstyle eq 'rat')
                   13510: 		|| ($embstyle eq 'prv')
                   13511: 		|| ($embstyle eq 'ign')) {
                   13512: 		#do nothing with these
                   13513: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13514: 		|| ($embstyle eq 'emb')
                   13515: 		|| ($embstyle eq 'wrp')) {
                   13516: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13517: 	    } elsif ($embstyle eq 'unk'
                   13518: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13519: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13520: 	    } else {
1.718     www      13521: #		&logthis("Got a blank emb style");
1.695     albertel 13522: 	    }
1.694     albertel 13523: 	}
1.1172.2.118.  .1(raebu 13524:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13525:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13526:     }
1.31      www      13527:     return $thisfn;
1.12      www      13528: }
                   13529: 
1.787     albertel 13530: sub clutter_with_no_wrapper {
                   13531:     my $uri = &clutter(shift);
                   13532:     if ($uri =~ m-^/adm/-) {
                   13533: 	$uri =~ s-^/adm/wrapper/-/-;
                   13534: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13535:     }
                   13536:     return $uri;
                   13537: }
                   13538: 
1.557     albertel 13539: sub freeze_escape {
                   13540:     my ($value)=@_;
                   13541:     if (ref($value)) {
                   13542: 	$value=&nfreeze($value);
                   13543: 	return '__FROZEN__'.&escape($value);
                   13544:     }
                   13545:     return &escape($value);
                   13546: }
                   13547: 
1.11      www      13548: 
1.557     albertel 13549: sub thaw_unescape {
                   13550:     my ($value)=@_;
                   13551:     if ($value =~ /^__FROZEN__/) {
                   13552: 	substr($value,0,10,undef);
                   13553: 	$value=&unescape($value);
                   13554: 	return &thaw($value);
                   13555:     }
                   13556:     return &unescape($value);
                   13557: }
                   13558: 
1.436     albertel 13559: sub correct_line_ends {
                   13560:     my ($result)=@_;
                   13561:     $$result =~s/\r\n/\n/mg;
                   13562:     $$result =~s/\r/\n/mg;
1.415     albertel 13563: }
1.1       albertel 13564: # ================================================================ Main Program
                   13565: 
1.184     www      13566: sub goodbye {
1.204     albertel 13567:    &logthis("Starting Shut down");
1.443     albertel 13568: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13569:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13570: #converted
1.599     albertel 13571: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13572:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13573: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13574: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13575: #1.1 only
1.870     albertel 13576: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13577: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13578: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13579: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13580:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13581:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13582:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13583:    &flushcourselogs();
                   13584:    &logthis("Shutting down");
                   13585: }
                   13586: 
1.852     albertel 13587: sub get_dns {
1.1172.2.17  raeburn  13588:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13589:     if (!$ignore_cache) {
                   13590: 	my ($content,$cached)=
                   13591: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13592: 	if ($cached) {
1.1172.2.17  raeburn  13593: 	    &$func($content,$hashref);
1.869     albertel 13594: 	    return;
                   13595: 	}
                   13596:     }
                   13597: 
                   13598:     my %alldns;
1.1172.2.96  raeburn  13599:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13600:         foreach my $dns (<$config>) {
                   13601: 	    next if ($dns !~ /^\^(\S*)/x);
                   13602:             my $line = $1;
                   13603:             my ($host,$protocol) = split(/:/,$line);
                   13604:             if ($protocol ne 'https') {
                   13605:                 $protocol = 'http';
                   13606:             }
                   13607: 	    $alldns{$host} = $protocol;
1.979     raeburn  13608:         }
1.1172.2.96  raeburn  13609:         close($config);
1.869     albertel 13610:     }
                   13611:     while (%alldns) {
1.1172.2.52  raeburn  13612: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13613: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13614:         $ua->timeout(30);
1.979     raeburn  13615: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13616: 	my $response=$ua->request($request);
1.979     raeburn  13617:         delete($alldns{$dns});
1.852     albertel 13618: 	next if ($response->is_error());
                   13619: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13620:         unless ($nocache) {
1.1172.2.23  raeburn  13621: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13622:         }
                   13623: 	&$func(\@content,$hashref);
1.869     albertel 13624: 	return;
1.852     albertel 13625:     }
1.871     albertel 13626:     my $which = (split('/',$url))[3];
                   13627:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13628:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13629:         my @content = <$config>;
                   13630:         &$func(\@content,$hashref);
                   13631:     }
1.1172.2.17  raeburn  13632:     return;
                   13633: }
                   13634: 
                   13635: # ------------------------------------------------------Get DNS checksums file
                   13636: sub parse_dns_checksums_tab {
                   13637:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13638:     my $lonhost = $perlvar{'lonHostID'};
                   13639:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13640:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13641:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13642:     my $webconfdir = '/etc/httpd/conf';
                   13643:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13644:         $webconfdir = '/etc/apache2';
                   13645:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13646:         if ($1 >= 10) {
                   13647:             $webconfdir = '/etc/apache2';
                   13648:         }
                   13649:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13650:         if ($1 >= 10.0) {
                   13651:             $webconfdir = '/etc/apache2';
                   13652:         }
                   13653:     }
1.1172.2.17  raeburn  13654:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13655:     my (%chksum,%revnum);
                   13656:     if (ref($lines) eq 'ARRAY') {
                   13657:         chomp(@{$lines});
1.1172.2.34  raeburn  13658:         my $version = shift(@{$lines});
                   13659:         if ($version eq $release) {
1.1172.2.17  raeburn  13660:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13661:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13662:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13663:                     if ($webconfdir eq '/etc/apache2') {
                   13664:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13665:                     }
                   13666:                 }
1.1172.2.34  raeburn  13667:                 $chksum{$file} = $shasum;
                   13668:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13669:             }
                   13670:             if (ref($hashref) eq 'HASH') {
                   13671:                 %{$hashref} = (
                   13672:                                 sums     => \%chksum,
                   13673:                                 versions => \%revnum,
                   13674:                               );
                   13675:             }
                   13676:         }
                   13677:     }
1.869     albertel 13678:     return;
1.852     albertel 13679: }
1.1172.2.17  raeburn  13680: 
                   13681: sub fetch_dns_checksums {
                   13682:     my %checksums;
1.1172.2.34  raeburn  13683:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13684:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13685:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13686:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13687:              \%checksums);
                   13688:     return \%checksums;
                   13689: }
                   13690: 
1.327     albertel 13691: # ------------------------------------------------------------ Read domain file
                   13692: {
1.852     albertel 13693:     my $loaded;
1.846     albertel 13694:     my %domain;
                   13695: 
1.852     albertel 13696:     sub parse_domain_tab {
                   13697: 	my ($lines) = @_;
                   13698: 	foreach my $line (@$lines) {
                   13699: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13700: 
1.846     albertel 13701: 	    chomp($line);
1.852     albertel 13702: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13703: 	    my %this_domain;
                   13704: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13705: 			       'lang_def', 'city', 'longi', 'lati',
                   13706: 			       'primary') {
                   13707: 		$this_domain{$field} = shift(@elements);
                   13708: 	    }
                   13709: 	    $domain{$name} = \%this_domain;
1.852     albertel 13710: 	}
                   13711:     }
1.864     albertel 13712: 
                   13713:     sub reset_domain_info {
                   13714: 	undef($loaded);
                   13715: 	undef(%domain);
                   13716:     }
                   13717: 
1.852     albertel 13718:     sub load_domain_tab {
1.1172.2.70  raeburn  13719: 	my ($ignore_cache,$nocache) = @_;
                   13720: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13721: 	my $fh;
1.1172.2.96  raeburn  13722: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13723: 	    my @lines = <$fh>;
                   13724: 	    &parse_domain_tab(\@lines);
1.448     albertel 13725: 	}
1.852     albertel 13726: 	close($fh);
                   13727: 	$loaded = 1;
1.327     albertel 13728:     }
1.846     albertel 13729: 
                   13730:     sub domain {
1.852     albertel 13731: 	&load_domain_tab() if (!$loaded);
                   13732: 
1.846     albertel 13733: 	my ($name,$what) = @_;
                   13734: 	return if ( !exists($domain{$name}) );
                   13735: 
                   13736: 	if (!$what) {
                   13737: 	    return $domain{$name}{'description'};
                   13738: 	}
                   13739: 	return $domain{$name}{$what};
                   13740:     }
1.974     raeburn  13741: 
                   13742:     sub domain_info {
                   13743:         &load_domain_tab() if (!$loaded);
                   13744:         return %domain;
                   13745:     }
                   13746: 
1.327     albertel 13747: }
                   13748: 
                   13749: 
1.1       albertel 13750: # ------------------------------------------------------------- Read hosts file
                   13751: {
1.838     albertel 13752:     my %hostname;
1.844     albertel 13753:     my %hostdom;
1.845     albertel 13754:     my %libserv;
1.852     albertel 13755:     my $loaded;
1.888     albertel 13756:     my %name_to_host;
1.1074    raeburn  13757:     my %internetdom;
1.1107    raeburn  13758:     my %LC_dns_serv;
1.852     albertel 13759: 
                   13760:     sub parse_hosts_tab {
                   13761: 	my ($file) = @_;
                   13762: 	foreach my $configline (@$file) {
                   13763: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13764:             chomp($configline);
                   13765: 	    if ($configline =~ /^\^/) {
                   13766:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13767:                     $LC_dns_serv{$1} = 1;
                   13768:                 }
                   13769:                 next;
                   13770:             }
1.1074    raeburn  13771: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13772: 	    $name=~s/\s//g;
                   13773: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13774:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13775:                     my $curr = $hostname{$id};
                   13776:                     my $skip;
                   13777:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13778:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13779:                             $skip = 1;
                   13780:                         } else {
                   13781:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13782:                         }
                   13783:                     }
                   13784:                     unless ($skip) {
                   13785:                         push(@{$name_to_host{$name}},$id);
                   13786:                     }
                   13787:                 } else {
                   13788:                     push(@{$name_to_host{$name}},$id);
                   13789:                 }
1.852     albertel 13790: 		$hostname{$id}=$name;
                   13791: 		$hostdom{$id}=$domain;
                   13792: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13793:                 if (defined($protocol)) {
                   13794:                     if ($protocol eq 'https') {
                   13795:                         $protocol{$id} = $protocol;
                   13796:                     } else {
                   13797:                         $protocol{$id} = 'http'; 
                   13798:                     }
1.968     raeburn  13799:                 } else {
1.969     raeburn  13800:                     $protocol{$id} = 'http';
1.968     raeburn  13801:                 }
1.1074    raeburn  13802:                 if (defined($intdom)) {
                   13803:                     $internetdom{$id} = $intdom;
                   13804:                 }
1.852     albertel 13805: 	    }
                   13806: 	}
                   13807:     }
1.864     albertel 13808:     
                   13809:     sub reset_hosts_info {
1.897     albertel 13810: 	&purge_remembered();
1.864     albertel 13811: 	&reset_domain_info();
                   13812: 	&reset_hosts_ip_info();
1.892     albertel 13813: 	undef(%name_to_host);
1.864     albertel 13814: 	undef(%hostname);
                   13815: 	undef(%hostdom);
                   13816: 	undef(%libserv);
                   13817: 	undef($loaded);
                   13818:     }
1.1       albertel 13819: 
1.852     albertel 13820:     sub load_hosts_tab {
1.1172.2.70  raeburn  13821: 	my ($ignore_cache,$nocache) = @_;
                   13822: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13823: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13824: 	my @config = <$config>;
                   13825: 	&parse_hosts_tab(\@config);
                   13826: 	close($config);
                   13827: 	$loaded=1;
1.1       albertel 13828:     }
1.852     albertel 13829: 
1.838     albertel 13830:     sub hostname {
1.852     albertel 13831: 	&load_hosts_tab() if (!$loaded);
                   13832: 
1.838     albertel 13833: 	my ($lonid) = @_;
                   13834: 	return $hostname{$lonid};
                   13835:     }
1.845     albertel 13836: 
1.838     albertel 13837:     sub all_hostnames {
1.852     albertel 13838: 	&load_hosts_tab() if (!$loaded);
                   13839: 
1.838     albertel 13840: 	return %hostname;
                   13841:     }
1.845     albertel 13842: 
1.888     albertel 13843:     sub all_names {
1.1172.2.70  raeburn  13844:         my ($ignore_cache,$nocache) = @_;
                   13845: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13846: 
                   13847: 	return %name_to_host;
                   13848:     }
                   13849: 
1.974     raeburn  13850:     sub all_host_domain {
                   13851:         &load_hosts_tab() if (!$loaded);
                   13852:         return %hostdom;
                   13853:     }
                   13854: 
1.845     albertel 13855:     sub is_library {
1.852     albertel 13856: 	&load_hosts_tab() if (!$loaded);
                   13857: 
1.845     albertel 13858: 	return exists($libserv{$_[0]});
                   13859:     }
                   13860: 
                   13861:     sub all_library {
1.852     albertel 13862: 	&load_hosts_tab() if (!$loaded);
                   13863: 
1.845     albertel 13864: 	return %libserv;
                   13865:     }
                   13866: 
1.1062    droeschl 13867:     sub unique_library {
                   13868: 	#2x reverse removes all hostnames that appear more than once
                   13869:         my %unique = reverse &all_library();
                   13870:         return reverse %unique;
                   13871:     }
                   13872: 
1.841     albertel 13873:     sub get_servers {
1.852     albertel 13874: 	&load_hosts_tab() if (!$loaded);
                   13875: 
1.841     albertel 13876: 	my ($domain,$type) = @_;
                   13877: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13878: 	                                          : %hostname;
                   13879: 	my %result;
1.842     albertel 13880: 	if (ref($domain) eq 'ARRAY') {
                   13881: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13882: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13883: 		    $result{$host} = $hostname;
                   13884: 		}
                   13885: 	    }
                   13886: 	} else {
                   13887: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13888: 		if ($hostdom{$host} eq $domain) {
                   13889: 		    $result{$host} = $hostname;
                   13890: 		}
1.841     albertel 13891: 	    }
                   13892: 	}
                   13893: 	return %result;
                   13894:     }
1.845     albertel 13895: 
1.1062    droeschl 13896:     sub get_unique_servers {
                   13897:         my %unique = reverse &get_servers(@_);
                   13898: 	return reverse %unique;
                   13899:     }
                   13900: 
1.844     albertel 13901:     sub host_domain {
1.852     albertel 13902: 	&load_hosts_tab() if (!$loaded);
                   13903: 
1.844     albertel 13904: 	my ($lonid) = @_;
                   13905: 	return $hostdom{$lonid};
                   13906:     }
                   13907: 
1.841     albertel 13908:     sub all_domains {
1.852     albertel 13909: 	&load_hosts_tab() if (!$loaded);
                   13910: 
1.841     albertel 13911: 	my %seen;
                   13912: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13913: 	return @uniq;
                   13914:     }
1.1074    raeburn  13915: 
                   13916:     sub internet_dom {
                   13917:         &load_hosts_tab() if (!$loaded);
                   13918: 
                   13919:         my ($lonid) = @_;
                   13920:         return $internetdom{$lonid};
                   13921:     }
1.1107    raeburn  13922: 
                   13923:     sub is_LC_dns {
                   13924:         &load_hosts_tab() if (!$loaded);
                   13925: 
                   13926:         my ($hostname) = @_;
                   13927:         return exists($LC_dns_serv{$hostname});
                   13928:     }
                   13929: 
1.1       albertel 13930: }
                   13931: 
1.847     albertel 13932: { 
                   13933:     my %iphost;
1.856     albertel 13934:     my %name_to_ip;
                   13935:     my %lonid_to_ip;
1.869     albertel 13936: 
1.847     albertel 13937:     sub get_hosts_from_ip {
                   13938: 	my ($ip) = @_;
                   13939: 	my %iphosts = &get_iphost();
                   13940: 	if (ref($iphosts{$ip})) {
                   13941: 	    return @{$iphosts{$ip}};
                   13942: 	}
                   13943: 	return;
1.839     albertel 13944:     }
1.864     albertel 13945:     
                   13946:     sub reset_hosts_ip_info {
                   13947: 	undef(%iphost);
                   13948: 	undef(%name_to_ip);
                   13949: 	undef(%lonid_to_ip);
                   13950:     }
1.856     albertel 13951: 
                   13952:     sub get_host_ip {
                   13953: 	my ($lonid) = @_;
                   13954: 	if (exists($lonid_to_ip{$lonid})) {
                   13955: 	    return $lonid_to_ip{$lonid};
                   13956: 	}
                   13957: 	my $name=&hostname($lonid);
                   13958:    	my $ip = gethostbyname($name);
                   13959: 	return if (!$ip || length($ip) ne 4);
                   13960: 	$ip=inet_ntoa($ip);
                   13961: 	$name_to_ip{$name}   = $ip;
                   13962: 	$lonid_to_ip{$lonid} = $ip;
                   13963: 	return $ip;
                   13964:     }
1.847     albertel 13965:     
                   13966:     sub get_iphost {
1.1172.2.70  raeburn  13967: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13968: 
1.869     albertel 13969: 	if (!$ignore_cache) {
                   13970: 	    if (%iphost) {
                   13971: 		return %iphost;
                   13972: 	    }
                   13973: 	    my ($ip_info,$cached)=
                   13974: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13975: 	    if ($cached) {
                   13976: 		%iphost      = %{$ip_info->[0]};
                   13977: 		%name_to_ip  = %{$ip_info->[1]};
                   13978: 		%lonid_to_ip = %{$ip_info->[2]};
                   13979: 		return %iphost;
                   13980: 	    }
                   13981: 	}
1.894     albertel 13982: 
                   13983: 	# get yesterday's info for fallback
                   13984: 	my %old_name_to_ip;
                   13985: 	my ($ip_info,$cached)=
                   13986: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13987: 	if ($cached) {
                   13988: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13989: 	}
                   13990: 
1.1172.2.70  raeburn  13991: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13992: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13993: 	    my $ip;
                   13994: 	    if (!exists($name_to_ip{$name})) {
                   13995: 		$ip = gethostbyname($name);
                   13996: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13997: 		    if (defined($old_name_to_ip{$name})) {
                   13998: 			$ip = $old_name_to_ip{$name};
                   13999: 			&logthis("Can't find $name defaulting to old $ip");
                   14000: 		    } else {
                   14001: 			&logthis("Name $name no IP found");
                   14002: 			next;
                   14003: 		    }
                   14004: 		} else {
                   14005: 		    $ip=inet_ntoa($ip);
1.847     albertel 14006: 		}
                   14007: 		$name_to_ip{$name} = $ip;
                   14008: 	    } else {
                   14009: 		$ip = $name_to_ip{$name};
1.653     albertel 14010: 	    }
1.888     albertel 14011: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14012: 		$lonid_to_ip{$id} = $ip;
                   14013: 	    }
                   14014: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14015: 	}
1.1172.2.70  raeburn  14016:         unless ($nocache) {
                   14017: 	    &do_cache_new('iphost','iphost',
                   14018: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14019: 		          48*60*60);
                   14020:         }
1.869     albertel 14021: 
1.847     albertel 14022: 	return %iphost;
1.598     albertel 14023:     }
                   14024: 
1.992     raeburn  14025:     #
                   14026:     #  Given a DNS returns the loncapa host name for that DNS 
                   14027:     # 
                   14028:     sub host_from_dns {
                   14029:         my ($dns) = @_;
                   14030:         my @hosts;
                   14031:         my $ip;
                   14032: 
1.993     raeburn  14033:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14034:             $ip = $name_to_ip{$dns};
                   14035:         }
                   14036:         if (!$ip) {
                   14037:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14038:             if (length($ip) == 4) { 
                   14039: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14040:             }
                   14041:         }
                   14042:         if ($ip) {
                   14043: 	    @hosts = get_hosts_from_ip($ip);
                   14044: 	    return $hosts[0];
                   14045:         }
                   14046:         return undef;
1.986     foxr     14047:     }
1.992     raeburn  14048: 
1.1074    raeburn  14049:     sub get_internet_names {
                   14050:         my ($lonid) = @_;
                   14051:         return if ($lonid eq '');
                   14052:         my ($idnref,$cached)=
                   14053:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14054:         if ($cached) {
                   14055:             return $idnref;
                   14056:         }
                   14057:         my $ip = &get_host_ip($lonid);
                   14058:         my @hosts = &get_hosts_from_ip($ip);
                   14059:         my %iphost = &get_iphost();
                   14060:         my (@idns,%seen);
                   14061:         foreach my $id (@hosts) {
                   14062:             my $dom = &host_domain($id);
                   14063:             my $prim_id = &domain($dom,'primary');
                   14064:             my $prim_ip = &get_host_ip($prim_id);
                   14065:             next if ($seen{$prim_ip});
                   14066:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14067:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14068:                     my $intdom = &internet_dom($id);
                   14069:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14070:                         push(@idns,$intdom);
                   14071:                     }
                   14072:                 }
                   14073:             }
                   14074:             $seen{$prim_ip} = 1;
                   14075:         }
1.1172.2.23  raeburn  14076:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14077:     }
                   14078: 
1.986     foxr     14079: }
                   14080: 
1.1079    raeburn  14081: sub all_loncaparevs {
1.1172.2.39  raeburn  14082:     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  14083: }
                   14084: 
1.1172.2.27  raeburn  14085: # ------------------------------------------------------- Read loncaparev table
                   14086: {
                   14087:     sub load_loncaparevs {
                   14088:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14089:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14090:                 while (my $configline=<$config>) {
                   14091:                     chomp($configline);
                   14092:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14093:                     $loncaparevs{$hostid}=$loncaparev;
                   14094:                 }
                   14095:                 close($config);
                   14096:             }
                   14097:         }
                   14098:     }
                   14099: }
                   14100: 
                   14101: # ----------------------------------------------------- Read serverhostID table
                   14102: {
                   14103:     sub load_serverhomeIDs {
                   14104:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14105:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14106:                 while (my $configline=<$config>) {
                   14107:                     chomp($configline);
                   14108:                     my ($name,$id)=split(/:/,$configline);
                   14109:                     $serverhomeIDs{$name}=$id;
                   14110:                 }
                   14111:                 close($config);
                   14112:             }
                   14113:         }
                   14114:     }
                   14115: }
                   14116: 
                   14117: 
1.862     albertel 14118: BEGIN {
                   14119: 
                   14120: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14121:     unless ($readit) {
                   14122: {
                   14123:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14124:     %perlvar = (%perlvar,%{$configvars});
                   14125: }
                   14126: 
                   14127: 
1.1       albertel 14128: # ------------------------------------------------------ Read spare server file
                   14129: {
1.1172.2.96  raeburn  14130:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14131: 
                   14132:     while (my $configline=<$config>) {
                   14133:        chomp($configline);
1.284     matthew  14134:        if ($configline) {
1.784     albertel 14135: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14136: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14137: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14138:        }
                   14139:     }
1.448     albertel 14140:     close($config);
1.1       albertel 14141: }
1.11      www      14142: # ------------------------------------------------------------ Read permissions
                   14143: {
1.1172.2.96  raeburn  14144:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14145: 
                   14146:     while (my $configline=<$config>) {
1.448     albertel 14147: 	chomp($configline);
                   14148: 	if ($configline) {
                   14149: 	    my ($role,$perm)=split(/ /,$configline);
                   14150: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14151: 	}
1.11      www      14152:     }
1.448     albertel 14153:     close($config);
1.11      www      14154: }
                   14155: 
                   14156: # -------------------------------------------- Read plain texts for permissions
                   14157: {
1.1172.2.96  raeburn  14158:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14159: 
                   14160:     while (my $configline=<$config>) {
1.448     albertel 14161: 	chomp($configline);
                   14162: 	if ($configline) {
1.742     raeburn  14163: 	    my ($short,@plain)=split(/:/,$configline);
                   14164:             %{$prp{$short}} = ();
                   14165: 	    if (@plain > 0) {
                   14166:                 $prp{$short}{'std'} = $plain[0];
                   14167:                 for (my $i=1; $i<@plain; $i++) {
                   14168:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14169:                 }
                   14170:             }
1.448     albertel 14171: 	}
1.135     www      14172:     }
1.448     albertel 14173:     close($config);
1.135     www      14174: }
                   14175: 
                   14176: # ---------------------------------------------------------- Read package table
                   14177: {
1.1172.2.96  raeburn  14178:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14179: 
                   14180:     while (my $configline=<$config>) {
1.483     albertel 14181: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14182: 	chomp($configline);
                   14183: 	my ($short,$plain)=split(/:/,$configline);
                   14184: 	my ($pack,$name)=split(/\&/,$short);
                   14185: 	if ($plain ne '') {
                   14186: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14187: 	    $packagetab{$short}=$plain; 
                   14188: 	}
1.11      www      14189:     }
1.448     albertel 14190:     close($config);
1.329     matthew  14191: }
                   14192: 
1.1172.2.27  raeburn  14193: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14194: 
1.1172.2.27  raeburn  14195: &load_loncaparevs();
                   14196: 
                   14197: # ------------------------------------------------------- Read serverhostID table
                   14198: 
                   14199: &load_serverhomeIDs();
1.1074    raeburn  14200: 
1.1172.2.27  raeburn  14201: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14202: {
                   14203:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14204:     if (-e $file) {
                   14205:         my $parser = HTML::LCParser->new($file);
                   14206:         while (my $token = $parser->get_token()) {
                   14207:             if ($token->[0] eq 'S') {
                   14208:                 my $item = $token->[1];
                   14209:                 my $name = $token->[2]{'name'};
                   14210:                 my $value = $token->[2]{'value'};
                   14211:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14212:                     my $release = $parser->get_text();
                   14213:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14214:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14215:                 }
                   14216:             }
                   14217:         }
                   14218:     }
1.1073    raeburn  14219: }
                   14220: 
1.1138    raeburn  14221: # ---------------------------------------------------------- Read managers table
                   14222: {
                   14223:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14224:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14225:             while (my $configline=<$config>) {
                   14226:                 chomp($configline);
                   14227:                 next if ($configline =~ /^\#/);
                   14228:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14229:                     $managerstab{$configline} = 1;
                   14230:                 }
                   14231:             }
                   14232:             close($config);
                   14233:         }
                   14234:     }
                   14235: }
                   14236: 
1.329     matthew  14237: # ------------- set up temporary directory
                   14238: {
1.1117    foxr     14239:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14240: 
1.11      www      14241: }
                   14242: 
1.1172.2.104  raeburn  14243: # ------------- set default texengine (domain default overrides this)
                   14244: {
                   14245:     $deftex = LONCAPA::texengine();
                   14246: }
                   14247: 
1.1172.2.114  raeburn  14248: # ------------- set default minimum length for passwords for internal auth users
                   14249: {
                   14250:     $passwdmin = LONCAPA::passwd_min();
                   14251: }
                   14252: 
1.794     albertel 14253: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14254: 				'compress_threshold'=> 20_000,
                   14255:  			        });
1.185     www      14256: 
1.281     www      14257: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14258: $dumpcount=0;
1.958     www      14259: $locknum=0;
1.22      www      14260: 
1.163     harris41 14261: &logtouch();
1.672     albertel 14262: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14263: $readit=1;
1.564     albertel 14264:     {
                   14265: 	use integer;
                   14266: 	my $test=(2**32)+1;
1.568     albertel 14267: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14268: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14269:     }
1.195     www      14270: }
1.1       albertel 14271: }
1.179     www      14272: 
1.1       albertel 14273: 1;
1.191     harris41 14274: __END__
                   14275: 
1.243     albertel 14276: =pod
                   14277: 
1.191     harris41 14278: =head1 NAME
                   14279: 
1.243     albertel 14280: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14281: 
                   14282: =head1 SYNOPSIS
                   14283: 
1.243     albertel 14284: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14285: 
                   14286:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14287: 
1.243     albertel 14288: Common parameters:
                   14289: 
                   14290: =over 4
                   14291: 
                   14292: =item *
                   14293: 
                   14294: $uname : an internal username (if $cname expecting a course Id specifically)
                   14295: 
                   14296: =item *
                   14297: 
                   14298: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14299: 
                   14300: =item *
                   14301: 
                   14302: $symb : a resource instance identifier
                   14303: 
                   14304: =item *
                   14305: 
                   14306: $namespace : the name of a .db file that contains the data needed or
                   14307: being set.
                   14308: 
                   14309: =back
                   14310: 
1.394     bowersj2 14311: =head1 OVERVIEW
1.191     harris41 14312: 
1.394     bowersj2 14313: lonnet provides subroutines which interact with the
                   14314: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14315: about classes, users, and resources.
1.243     albertel 14316: 
                   14317: For many of these objects you can also use this to store data about
                   14318: them or modify them in various ways.
1.191     harris41 14319: 
1.394     bowersj2 14320: =head2 Symbs
1.191     harris41 14321: 
1.394     bowersj2 14322: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14323: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14324: map, the resource number of the resource in the map, and the URL of
                   14325: the resource itself. The latter is somewhat redundant, but might help
                   14326: if maps change.
                   14327: 
                   14328: An example is
                   14329: 
                   14330:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14331: 
                   14332: The respective map entry is
                   14333: 
                   14334:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14335:   title="Problem 2">
                   14336:  </resource>
                   14337: 
                   14338: Symbs are used by the random number generator, as well as to store and
                   14339: restore data specific to a certain instance of for example a problem.
                   14340: 
                   14341: =head2 Storing And Retrieving Data
                   14342: 
                   14343: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14344: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14345: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14346: is is the non-critical message twin of cstore. These functions are for
                   14347: handlers to store a perl hash to a user's permanent data space in an
                   14348: easy manner, and to retrieve it again on another call. It is expected
                   14349: that a handler would use this once at the beginning to retrieve data,
                   14350: and then again once at the end to send only the new data back.
                   14351: 
                   14352: The data is stored in the user's data directory on the user's
                   14353: homeserver under the ID of the course.
                   14354: 
                   14355: The hash that is returned by restore will have all of the previous
                   14356: value for all of the elements of the hash.
                   14357: 
                   14358: Example:
                   14359: 
                   14360:  #creating a hash
                   14361:  my %hash;
                   14362:  $hash{'foo'}='bar';
                   14363: 
                   14364:  #storing it
                   14365:  &Apache::lonnet::cstore(\%hash);
                   14366: 
                   14367:  #changing a value
                   14368:  $hash{'foo'}='notbar';
                   14369: 
                   14370:  #adding a new value
                   14371:  $hash{'bar'}='foo';
                   14372:  &Apache::lonnet::cstore(\%hash);
                   14373: 
                   14374:  #retrieving the hash
                   14375:  my %history=&Apache::lonnet::restore();
                   14376: 
                   14377:  #print the hash
                   14378:  foreach my $key (sort(keys(%history))) {
                   14379:    print("\%history{$key} = $history{$key}");
                   14380:  }
                   14381: 
                   14382: Will print out:
1.191     harris41 14383: 
1.394     bowersj2 14384:  %history{1:foo} = bar
                   14385:  %history{1:keys} = foo:timestamp
                   14386:  %history{1:timestamp} = 990455579
                   14387:  %history{2:bar} = foo
                   14388:  %history{2:foo} = notbar
                   14389:  %history{2:keys} = foo:bar:timestamp
                   14390:  %history{2:timestamp} = 990455580
                   14391:  %history{bar} = foo
                   14392:  %history{foo} = notbar
                   14393:  %history{timestamp} = 990455580
                   14394:  %history{version} = 2
                   14395: 
                   14396: Note that the special hash entries C<keys>, C<version> and
                   14397: C<timestamp> were added to the hash. C<version> will be equal to the
                   14398: total number of versions of the data that have been stored. The
                   14399: C<timestamp> attribute will be the UNIX time the hash was
                   14400: stored. C<keys> is available in every historical section to list which
                   14401: keys were added or changed at a specific historical revision of a
                   14402: hash.
                   14403: 
                   14404: B<Warning>: do not store the hash that restore returns directly. This
                   14405: will cause a mess since it will restore the historical keys as if the
                   14406: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14407: 
1.394     bowersj2 14408: Calling convention:
1.191     harris41 14409: 
1.1172.2.27  raeburn  14410:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14411:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14412: 
1.394     bowersj2 14413: For more detailed information, see lonnet specific documentation.
1.191     harris41 14414: 
1.394     bowersj2 14415: =head1 RETURN MESSAGES
1.191     harris41 14416: 
1.394     bowersj2 14417: =over 4
1.191     harris41 14418: 
1.394     bowersj2 14419: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14420: 
1.394     bowersj2 14421: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14422: when the connection is brought back up
1.191     harris41 14423: 
1.394     bowersj2 14424: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14425: for later delivery
1.191     harris41 14426: 
1.967     bisitz   14427: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14428: 
1.394     bowersj2 14429: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14430: that was requested
1.191     harris41 14431: 
1.243     albertel 14432: =back
1.191     harris41 14433: 
1.243     albertel 14434: =head1 PUBLIC SUBROUTINES
1.191     harris41 14435: 
1.243     albertel 14436: =head2 Session Environment Functions
1.191     harris41 14437: 
1.243     albertel 14438: =over 4
1.191     harris41 14439: 
1.394     bowersj2 14440: =item * 
                   14441: X<appenv()>
1.949     raeburn  14442: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14443: the user envirnoment file, and will be restored for each access this
1.620     albertel 14444: user makes during this session, also modifies the %env for the current
1.949     raeburn  14445: process. Optional rolesarrayref - if defined contains a reference to an array
                   14446: of roles which are exempt from the restriction on modifying user.role entries 
                   14447: in the user's environment.db and in %env.    
1.191     harris41 14448: 
                   14449: =item *
1.394     bowersj2 14450: X<delenv()>
1.987     raeburn  14451: B<delenv($delthis,$regexp)>: removes all items from the session
                   14452: environment file that begin with $delthis. If the 
                   14453: optional second arg - $regexp - is true, $delthis is treated as a 
                   14454: regular expression, otherwise \Q$delthis\E is used. 
                   14455: The values are also deleted from the current processes %env.
1.191     harris41 14456: 
1.795     albertel 14457: =item * get_env_multiple($name) 
                   14458: 
                   14459: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14460: values may be defined and end up as an array ref.
                   14461: 
                   14462: returns an array of values
                   14463: 
1.243     albertel 14464: =back
                   14465: 
                   14466: =head2 User Information
1.191     harris41 14467: 
1.243     albertel 14468: =over 4
1.191     harris41 14469: 
                   14470: =item *
1.394     bowersj2 14471: X<queryauthenticate()>
                   14472: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14473: authentication scheme
                   14474: 
                   14475: =item *
1.394     bowersj2 14476: X<authenticate()>
1.1073    raeburn  14477: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14478: authenticate user from domain's lib servers (first use the current
                   14479: one). C<$upass> should be the users password.
1.1073    raeburn  14480: $checkdefauth is optional (value is 1 if a check should be made to
                   14481:    authenticate user using default authentication method, and allow
                   14482:    account creation if username does not have account in the domain).
                   14483: $clientcancheckhost is optional (value is 1 if checking whether the
                   14484:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14485: 
                   14486: =item *
1.394     bowersj2 14487: X<homeserver()>
                   14488: B<homeserver($uname,$udom)>: find the server which has
                   14489: the user's directory and files (there must be only one), this caches
                   14490: the answer, and also caches if there is a borken connection.
1.191     harris41 14491: 
                   14492: =item *
1.394     bowersj2 14493: X<idget()>
                   14494: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14495: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14496: username, and only 1 username per ID in a specific domain) (returns
                   14497: hash: id=>name,id=>name)
1.191     harris41 14498: 
                   14499: =item *
1.394     bowersj2 14500: X<idrget()>
                   14501: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14502: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14503: 
                   14504: =item *
1.394     bowersj2 14505: X<idput()>
                   14506: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14507: 
                   14508: =item *
1.394     bowersj2 14509: X<rolesinit()>
1.1169    droeschl 14510: B<rolesinit($udom,$username)>: get user privileges.
                   14511: returns user role, first access and timer interval hashes
1.243     albertel 14512: 
                   14513: =item *
1.1171    droeschl 14514: X<privileged()>
                   14515: B<privileged($username,$domain)>: returns a true if user has a
                   14516: privileged and active role (i.e. su or dc), false otherwise.
                   14517: 
                   14518: =item *
1.551     albertel 14519: X<getsection()>
                   14520: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14521: course $cname, return section name/number or '' for "not in course"
                   14522: and '-1' for "no section"
                   14523: 
                   14524: =item *
1.394     bowersj2 14525: X<userenvironment()>
                   14526: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14527: passed in @what from the requested user's environment, returns a hash
                   14528: 
1.858     raeburn  14529: =item * 
                   14530: X<userlog_query()>
1.859     albertel 14531: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14532: activity.log file. %filters defines filters applied when parsing the
                   14533: log file. These can be start or end timestamps, or the type of action
                   14534: - log to look for Login or Logout events, check for Checkin or
                   14535: Checkout, role for role selection. The response is in the form
                   14536: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14537: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14538: 
1.243     albertel 14539: =back
                   14540: 
                   14541: =head2 User Roles
                   14542: 
                   14543: =over 4
                   14544: 
                   14545: =item *
                   14546: 
1.1172.2.65  raeburn  14547: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14548: returns codes for allowed actions.
                   14549: 
                   14550: The first argument is required, all others are optional.
                   14551: 
                   14552: $priv is the privilege being checked.
                   14553: $uri contains additional information about what is being checked for access (e.g.,
                   14554: URL, course ID etc.).
                   14555: $symb is the unique resource instance identifier in a course; if needed,
                   14556: but not provided, it will be retrieved via a call to &symbread().
                   14557: $role is the role for which a priv is being checked (only used if priv is evb).
                   14558: $clientip is the user's IP address (only used when checking for access to portfolio
                   14559: files).
                   14560: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14561: prevents recursive calls to &allowed.
                   14562: 
1.243     albertel 14563:  F: full access
                   14564:  U,I,K: authentication modes (cxx only)
                   14565:  '': forbidden
                   14566:  1: user needs to choose course
                   14567:  2: browse allowed
1.766     albertel 14568:  A: passphrase authentication needed
1.1172.2.65  raeburn  14569:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14570: 
                   14571: =item *
                   14572: 
1.1172.2.13  raeburn  14573: constructaccess($url,$setpriv) : check for access to construction space URL
                   14574: 
                   14575: See if the owner domain and name in the URL match those in the
                   14576: expected environment.  If so, return three element list
                   14577: ($ownername,$ownerdomain,$ownerhome).
                   14578: 
                   14579: Otherwise return the null string.
                   14580: 
                   14581: If second argument 'setpriv' is true, it assigns the privileges,
                   14582: and returns the same three element list, unless the owner has
                   14583: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14584: in which case the null string is returned.
                   14585: 
                   14586: =item *
                   14587: 
1.1172.2.84  raeburn  14588: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14589: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14590: for system, domain, and course level. $uname and $udom are optional (current
                   14591: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14592: 
                   14593: =item *
                   14594: 
1.988     raeburn  14595: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14596: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14597: $type is Course (default) or Community.
1.988     raeburn  14598: If $forcedefault evaluates to true, text returned will be default 
                   14599: text for $type. Otherwise, if this is a course, the text returned 
                   14600: will be a custom name for the role (if defined in the course's 
                   14601: environment).  If no custom name is defined the default is returned.
                   14602:    
1.832     raeburn  14603: =item *
                   14604: 
1.1172.2.23  raeburn  14605: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14606: All arguments are optional. Returns a hash of a roles, either for
                   14607: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14608: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14609: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14610: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14611: For each key, value is set to colon-separated start and end times for
                   14612: the role.  If no username and domain are specified, will default to
1.934     raeburn  14613: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14614: of role statuses (active, future or previous), roles 
                   14615: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14616: to restrict the list of roles reported. If no array ref is 
                   14617: provided for types, will default to return only active roles.
1.834     albertel 14618: 
1.1172.2.13  raeburn  14619: =item *
                   14620: 
                   14621: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14622: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14623: 
                   14624: Additional optional arguments are: $type (if role checking is to be restricted
                   14625: to certain user status types -- previous (expired roles), active (currently
                   14626: available roles) or future (roles available in the future), and
                   14627: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14628: have active Domain Coordinator role in course's domain or in additional
                   14629: domains (specified in 'Domains to check for privileged users' in course
                   14630: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14631: 
                   14632: =item *
                   14633: 
                   14634: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14635: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14636: $possdomains and $possroles are optional array refs -- to domains to check and
                   14637: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14638: users' roles.db to check for a dc or su role in any domain. This can be
                   14639: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14640: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14641: this then allows &privileged_by_domain() to be used, which caches the identity
                   14642: of privileged users, eliminating the need for repeated calls to &dump().
                   14643: 
                   14644: =item *
                   14645: 
                   14646: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14647: where the outer hash keys are domains specified in the $possdomains array ref,
                   14648: next inner hash keys are privileged roles specified in the $roles array ref,
                   14649: and the innermost hash contains key = value pairs for username:domain = end:start
                   14650: for active or future "privileged" users with that role in that domain. To avoid
                   14651: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14652: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14653: 
1.243     albertel 14654: =back
                   14655: 
                   14656: =head2 User Modification
                   14657: 
                   14658: =over 4
                   14659: 
                   14660: =item *
                   14661: 
1.957     raeburn  14662: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14663: user for the level given by URL.  Optional start and end dates (leave empty
                   14664: string or zero for "no date")
1.191     harris41 14665: 
                   14666: =item *
                   14667: 
1.243     albertel 14668: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14669: change a users, password, possible return values are: ok,
                   14670: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14671: refused
1.191     harris41 14672: 
                   14673: =item *
                   14674: 
1.243     albertel 14675: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14676: 
                   14677: =item *
                   14678: 
1.1058    raeburn  14679: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14680:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14681: 
                   14682: will update user information (firstname,middlename,lastname,generation,
                   14683: permanentemail), and if forceid is true, student/employee ID also.
                   14684: A user's institutional affiliation(s) can also be updated.
                   14685: User information fields will not be overwritten with empty entries 
                   14686: unless the field is included in the $candelete array reference.
                   14687: This array is included when a single user is modified via "Manage Users",
                   14688: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14689: 
                   14690: =item *
                   14691: 
1.286     matthew  14692: modifystudent
                   14693: 
1.957     raeburn  14694: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14695: The course id is resolved based on the current user's environment.  
                   14696: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14697: associated with a course.
                   14698: 
1.297     matthew  14699: This call is essentially a wrapper for lonnet::modifyuser and
                   14700: lonnet::modify_student_enrollment
1.286     matthew  14701: 
                   14702: Inputs: 
                   14703: 
                   14704: =over 4
                   14705: 
1.957     raeburn  14706: =item B<$udom> Student's loncapa domain
1.286     matthew  14707: 
1.957     raeburn  14708: =item B<$uname> Student's loncapa login name
1.286     matthew  14709: 
1.964     bisitz   14710: =item B<$uid> Student/Employee ID
1.286     matthew  14711: 
1.957     raeburn  14712: =item B<$umode> Student's authentication mode
1.286     matthew  14713: 
1.957     raeburn  14714: =item B<$upass> Student's password
1.286     matthew  14715: 
1.957     raeburn  14716: =item B<$first> Student's first name
1.286     matthew  14717: 
1.957     raeburn  14718: =item B<$middle> Student's middle name
1.286     matthew  14719: 
1.957     raeburn  14720: =item B<$last> Student's last name
1.286     matthew  14721: 
1.957     raeburn  14722: =item B<$gene> Student's generation
1.286     matthew  14723: 
1.957     raeburn  14724: =item B<$usec> Student's section in course
1.286     matthew  14725: 
                   14726: =item B<$end> Unix time of the roles expiration
                   14727: 
                   14728: =item B<$start> Unix time of the roles start date
                   14729: 
                   14730: =item B<$forceid> If defined, allow $uid to be changed
                   14731: 
                   14732: =item B<$desiredhome> server to use as home server for student
                   14733: 
1.957     raeburn  14734: =item B<$email> Student's permanent e-mail address
                   14735: 
                   14736: =item B<$type> Type of enrollment (auto or manual)
                   14737: 
1.963     raeburn  14738: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14739: 
                   14740: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14741: 
1.963     raeburn  14742: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14743: 
1.963     raeburn  14744: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14745: 
1.1172.2.19  raeburn  14746: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14747: 
                   14748: =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  14749: 
1.286     matthew  14750: =back
1.297     matthew  14751: 
                   14752: =item *
                   14753: 
                   14754: modify_student_enrollment
                   14755: 
1.1172.2.31  raeburn  14756: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14757: 'role.request.course' must be defined for this function to proceed.
                   14758: 
                   14759: Inputs:
                   14760: 
                   14761: =over 4
                   14762: 
1.1172.2.31  raeburn  14763: =item $udom, student's domain
1.297     matthew  14764: 
1.1172.2.31  raeburn  14765: =item $uname, student's name
1.297     matthew  14766: 
1.1172.2.31  raeburn  14767: =item $uid, student's user id
1.297     matthew  14768: 
1.1172.2.31  raeburn  14769: =item $first, student's first name
1.297     matthew  14770: 
                   14771: =item $middle
                   14772: 
                   14773: =item $last
                   14774: 
                   14775: =item $gene
                   14776: 
                   14777: =item $usec
                   14778: 
                   14779: =item $end
                   14780: 
                   14781: =item $start
                   14782: 
1.957     raeburn  14783: =item $type
                   14784: 
                   14785: =item $locktype
                   14786: 
                   14787: =item $cid
                   14788: 
                   14789: =item $selfenroll
                   14790: 
                   14791: =item $context
                   14792: 
1.1172.2.19  raeburn  14793: =item $credits, number of credits student will earn from this class
                   14794: 
1.1172.2.76  raeburn  14795: =item $instsec, institutional course section code for student
                   14796: 
1.297     matthew  14797: =back
                   14798: 
1.191     harris41 14799: 
                   14800: =item *
                   14801: 
1.243     albertel 14802: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14803: custom role; give a custom role to a user for the level given by URL.  Specify
                   14804: name and domain of role author, and role name
1.191     harris41 14805: 
                   14806: =item *
                   14807: 
1.243     albertel 14808: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14809: 
                   14810: =item *
                   14811: 
1.243     albertel 14812: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14813: 
                   14814: =back
                   14815: 
                   14816: =head2 Course Infomation
                   14817: 
                   14818: =over 4
1.191     harris41 14819: 
                   14820: =item *
                   14821: 
1.1118    foxr     14822: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14823: specified course id, including all environment settings for the
                   14824: course, the description of the course will be in the hash under the
                   14825: key 'description'
1.191     harris41 14826: 
1.1118    foxr     14827: $options is an optional parameter that if supplied is a hash reference that controls
                   14828: what how this function works.  It has the following key/values:
                   14829: 
                   14830: =over 4
                   14831: 
                   14832: =item freshen_cache
                   14833: 
                   14834: If defined, and the environment cache for the course is valid, it is 
                   14835: returned in the returned hash.
                   14836: 
                   14837: =item one_time
                   14838: 
                   14839: If defined, the last cache time is set to _now_
                   14840: 
                   14841: =item user
                   14842: 
                   14843: If defined, the supplied username is used instead of the current user.
                   14844: 
                   14845: 
                   14846: =back
                   14847: 
1.191     harris41 14848: =item *
                   14849: 
1.624     albertel 14850: resdata($name,$domain,$type,@which) : request for current parameter
                   14851: setting for a specific $type, where $type is either 'course' or 'user',
                   14852: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14853: answers for 10 minutes.
1.243     albertel 14854: 
1.877     foxr     14855: =item *
                   14856: 
                   14857: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14858: data base, returning a hash that is keyed by the resource name and has
                   14859: values that are the resource value.  I believe that the timestamps and
                   14860: versions are also returned.
                   14861: 
1.1172.2.31  raeburn  14862: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14863: supplemental content area. This routine caches the number of files for
                   14864: 10 minutes.
                   14865: 
1.243     albertel 14866: =back
                   14867: 
                   14868: =head2 Course Modification
                   14869: 
                   14870: =over 4
1.191     harris41 14871: 
                   14872: =item *
                   14873: 
1.243     albertel 14874: writecoursepref($courseid,%prefs) : write preferences (environment
                   14875: database) for a course
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.1011    raeburn  14879: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14880: 
                   14881: =item *
                   14882: 
1.1038    raeburn  14883: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14884: 
1.1167    droeschl 14885: =item *
                   14886: 
                   14887: is_course($courseid), is_course($cdom, $cnum)
                   14888: 
                   14889: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14890: two component version $cdom, $cnum. It checks if the specified course exists.
                   14891: 
                   14892: Returns:
                   14893:     undef if the course doesn't exist, otherwise
                   14894:     in scalar context the combined courseid.
                   14895:     in list context the two components of the course identifier, domain and 
                   14896:     courseid.    
                   14897: 
1.243     albertel 14898: =back
                   14899: 
1.1172.2.109  raeburn  14900: =head2 Bubblesheet Configuration
                   14901: 
                   14902: =over 4
                   14903: 
                   14904: =item *
                   14905: 
                   14906: get_scantron_config($which)
                   14907: 
                   14908: $which - the name of the configuration to parse from the file.
                   14909: 
                   14910: Parses and returns the bubblesheet configuration line selected as a
                   14911: hash of configuration file fields.
                   14912: 
                   14913: 
                   14914: Returns:
                   14915:     If the named configuration is not in the file, an empty
                   14916:     hash is returned.
                   14917: 
                   14918:     a hash with the fields
                   14919:       name         - internal name for the this configuration setup
                   14920:       description  - text to display to operator that describes this config
                   14921:       CODElocation - if 0 or the string 'none'
                   14922:                           - no CODE exists for this config
                   14923:                      if -1 || the string 'letter'
                   14924:                           - a CODE exists for this config and is
                   14925:                             a string of letters
                   14926:                      Unsupported value (but planned for future support)
                   14927:                           if a positive integer
                   14928:                                - The CODE exists as the first n items from
                   14929:                                  the question section of the form
                   14930:                           if the string 'number'
                   14931:                                - The CODE exists for this config and is
                   14932:                                  a string of numbers
                   14933:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14934:                      the CODE starts
                   14935:       CODElength  - length of the CODE
                   14936:       IDstart     - column where the student/employee ID starts
                   14937:       IDlength    - length of the student/employee ID info
                   14938:       Qstart      - column where the information from the bubbled
                   14939:                     'questions' start
                   14940:       Qlength     - number of columns comprising a single bubble line from
                   14941:                     the sheet. (usually either 1 or 10)
                   14942:       Qon         - either a single character representing the character used
                   14943:                     to signal a bubble was chosen in the positional setup, or
                   14944:                     the string 'letter' if the letter of the chosen bubble is
                   14945:                     in the final, or 'number' if a number representing the
                   14946:                     chosen bubble is in the file (1->A 0->J)
                   14947:       Qoff        - the character used to represent that a bubble was
                   14948:                     left blank
                   14949:       PaperID     - if the scanning process generates a unique number for each
                   14950:                     sheet scanned the column that this ID number starts in
                   14951:       PaperIDlength - number of columns that comprise the unique ID number
                   14952:                       for the sheet of paper
                   14953:       FirstName   - column that the first name starts in
                   14954:       FirstNameLength - number of columns that the first name spans
                   14955:       LastName    - column that the last name starts in
                   14956:       LastNameLength - number of columns that the last name spans
                   14957:       BubblesPerRow - number of bubbles available in each row used to
                   14958:                       bubble an answer. (If not specified, 10 assumed).
                   14959: 
                   14960: 
                   14961: =item *
                   14962: 
                   14963: get_scantronformat_file($cdom)
                   14964: 
                   14965: $cdom - the course's domain (optional); if not supplied, uses
                   14966: domain for current $env{'request.course.id'}.
                   14967: 
                   14968: Returns an array containing lines from the scantron format file for
                   14969: the domain of the course.
                   14970: 
                   14971: If a url for a custom.tab file is listed in domain's configuration.db,
                   14972: lines are from this file.
                   14973: 
                   14974: Otherwise, if a default.tab has been published in RES space by the
                   14975: domainconfig user, lines are from this file.
                   14976: 
                   14977: Otherwise, fall back to getting lines from the legacy file on the
                   14978: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14979: 
                   14980: =back
                   14981: 
1.243     albertel 14982: =head2 Resource Subroutines
                   14983: 
                   14984: =over 4
1.191     harris41 14985: 
                   14986: =item *
                   14987: 
1.243     albertel 14988: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14989: 
                   14990: =item *
                   14991: 
1.243     albertel 14992: repcopy($filename) : subscribes to the requested file, and attempts to
                   14993: replicate from the owning library server, Might return
1.607     raeburn  14994: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14995: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14996: resource. Expects the local filesystem pathname
                   14997: (/home/httpd/html/res/....)
                   14998: 
                   14999: =back
                   15000: 
                   15001: =head2 Resource Information
                   15002: 
                   15003: =over 4
1.191     harris41 15004: 
                   15005: =item *
                   15006: 
1.1172.2.28  raeburn  15007: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15008: and returns the value of a variety of different possible values,
                   15009: $varname should be a request string, and the other parameters can be
                   15010: used to specify who and what one is asking about. Ordinarily, $cid 
                   15011: does not need to be specified, as it is retrived from 
                   15012: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15013: within lonuserstate::loadmap() when initializing a course, before
                   15014: $env{'request.course.id'} has been set, so it needs to be provided
                   15015: in that one case.
1.243     albertel 15016: 
                   15017: Possible values for $varname are environment.lastname (or other item
                   15018: from the envirnment hash), user.name (or someother aspect about the
                   15019: user), resource.0.maxtries (or some other part and parameter of a
                   15020: resource)
1.204     albertel 15021: 
                   15022: =item *
                   15023: 
1.243     albertel 15024: directcondval($number) : get current value of a condition; reads from a state
                   15025: string
1.204     albertel 15026: 
                   15027: =item *
                   15028: 
1.243     albertel 15029: condval($condidx) : value of condition index based on state
1.204     albertel 15030: 
                   15031: =item *
                   15032: 
1.243     albertel 15033: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15034: resource's metadata, $what should be either a specific key, or either
                   15035: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15036: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15037: 
                   15038: this function automatically caches all requests
1.191     harris41 15039: 
                   15040: =item *
                   15041: 
1.243     albertel 15042: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15043: network of library servers; returns file handle of where SQL and regex results
                   15044: will be stored for query
1.191     harris41 15045: 
                   15046: =item *
                   15047: 
1.1172.2.66  raeburn  15048: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15049: return symbolic list entry (all arguments optional).
                   15050: 
                   15051: Args: filename is the filename (including path) for the file for which a symb
                   15052: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15053: to check access status if more than one resource was found in the bighash
                   15054: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15055: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15056: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15057: cause possible symbs to be checked to determine if they are subject to content
                   15058: blocking, if so they will not be included as possible symbs; possibles is a
                   15059: ref to a hash, which, as a side effect, will be populated with all possible
                   15060: symbs (content blocking not tested).
                   15061: 
1.243     albertel 15062: returns the data handle
1.191     harris41 15063: 
                   15064: =item *
                   15065: 
1.1172.2.17  raeburn  15066: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15067: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15068: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15069: on failure, user must be in a course, as it assumes the existence of
                   15070: the course initial hash, and uses $env('request.course.id'}.  The third
                   15071: arg is an optional reference to a scalar.  If this arg is passed in the
                   15072: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15073: encrypted; otherwise it will be null.
1.243     albertel 15074: 
1.191     harris41 15075: =item *
                   15076: 
1.243     albertel 15077: symbclean($symb) : removes versions numbers from a symb, returns the
                   15078: cleaned symb
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15083: course map, user must be in a course for it to work.
1.191     harris41 15084: 
                   15085: =item *
                   15086: 
1.243     albertel 15087: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15088: 
                   15089: =item *
                   15090: 
1.243     albertel 15091: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15092: a random seed, all arguments are optional, if they aren't sent it uses the
                   15093: environment to derive them. Note: if symb isn't sent and it can't get one
                   15094: from &symbread it will use the current time as its return value
1.191     harris41 15095: 
                   15096: =item *
                   15097: 
1.243     albertel 15098: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15099: unfakeable, receipt
1.191     harris41 15100: 
                   15101: =item *
                   15102: 
1.620     albertel 15103: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15104: 
                   15105: =item *
                   15106: 
1.243     albertel 15107: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15108: 
                   15109: =item *
                   15110: 
1.243     albertel 15111: 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 15112: 
                   15113: =item *
                   15114: 
1.243     albertel 15115: 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 15116: 
                   15117: =item *
                   15118: 
1.243     albertel 15119: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15120: 
                   15121: =item *
                   15122: 
1.243     albertel 15123: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15124: forcing spreadsheet to reevaluate the resource scores next time.
                   15125: 
1.1172.2.13  raeburn  15126: =item *
                   15127: 
                   15128: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15129: when viewing in course context.
                   15130: 
                   15131:  input: six args -- filename (decluttered), course number, course domain,
                   15132:                     url, symb (if registered) and group (if this is a
                   15133:                     group item -- e.g., bulletin board, group page etc.).
                   15134: 
                   15135:  output: array of five scalars --
                   15136:          $cfile -- url for file editing if editable on current server
                   15137:          $home -- homeserver of resource (i.e., for author if published,
                   15138:                                           or course if uploaded.).
                   15139:          $switchserver --  1 if server switch will be needed.
                   15140:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15141:          $forceview -- 1 if icon/link should be to go to view mode
                   15142: 
                   15143: =item *
                   15144: 
                   15145: is_course_upload($file,$cnum,$cdom)
                   15146: 
                   15147: Used in course context to determine if current file was uploaded to
                   15148: the course (i.e., would be found in /userfiles/docs on the course's
                   15149: homeserver.
                   15150: 
                   15151:   input: 3 args -- filename (decluttered), course number and course domain.
                   15152:   output: boolean -- 1 if file was uploaded.
                   15153: 
1.243     albertel 15154: =back
                   15155: 
                   15156: =head2 Storing/Retreiving Data
                   15157: 
                   15158: =over 4
1.191     harris41 15159: 
                   15160: =item *
                   15161: 
1.1172.2.64  raeburn  15162: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15163: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15164: the remaining args aren't required and if they aren't passed or are '' they will
                   15165: be derived from the env (with the exception of $laststore, which is an
                   15166: optional arg used when a user's submission is stored in grading).
                   15167: $laststore is $version=$timestamp, where $version is the most recent version
                   15168: number retrieved for the corresponding $symb in the $namespace db file, and
                   15169: $timestamp is the timestamp for that transaction (UNIX time).
                   15170: $laststore is currently only passed when cstore() is called by
                   15171: structuretags::finalize_storage().
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.1172.2.64  raeburn  15175: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15176: but uses critical subroutine
1.191     harris41 15177: 
                   15178: =item *
                   15179: 
1.243     albertel 15180: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15181: all args are optional
1.191     harris41 15182: 
                   15183: =item *
                   15184: 
1.717     albertel 15185: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15186: dumps the complete (or key matching regexp) namespace into a hash
                   15187: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15188: normally &store()ed into
                   15189: 
                   15190: $range should be either an integer '100' (give me the first 100
                   15191:                                            matching records)
                   15192:               or be  two integers sperated by a - with no spaces
                   15193:                  '30-50' (give me the 30th through the 50th matching
                   15194:                           records)
                   15195: 
                   15196: 
                   15197: =item *
                   15198: 
1.1172.2.59  raeburn  15199: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15200: replaces a &store() version of data with a replacement set of data
                   15201: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15202: reference. If $tolog is true, the transaction is logged in the courselog
                   15203: with an action=PUTSTORE.
1.717     albertel 15204: 
                   15205: =item *
                   15206: 
1.243     albertel 15207: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15208: works very similar to store/cstore, but all data is stored in a
                   15209: temporary location and can be reset using tmpreset, $storehash should
                   15210: be a hash reference, returns nothing on success
1.191     harris41 15211: 
                   15212: =item *
                   15213: 
1.243     albertel 15214: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15215: similar to restore, but all data is stored in a temporary location and
                   15216: can be reset using tmpreset. Returns a hash of values on success,
                   15217: error string otherwise.
1.191     harris41 15218: 
                   15219: =item *
                   15220: 
1.243     albertel 15221: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15222: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15223: 
                   15224: =item *
                   15225: 
1.243     albertel 15226: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15227: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15228: 
                   15229: =item *
                   15230: 
1.243     albertel 15231: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15232: namesp ($udom and $uname are optional)
1.191     harris41 15233: 
                   15234: =item *
                   15235: 
1.702     albertel 15236: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15237: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15238: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15239: 
1.702     albertel 15240: $range should be either an integer '100' (give me the first 100
                   15241:                                            matching records)
                   15242:               or be  two integers sperated by a - with no spaces
                   15243:                  '30-50' (give me the 30th through the 50th matching
                   15244:                           records)
1.449     matthew  15245: =item *
                   15246: 
                   15247: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15248: $store can be a scalar, an array reference, or if the amount to be 
                   15249: incremented is > 1, a hash reference.
                   15250: 
                   15251: ($udom and $uname are optional)
1.191     harris41 15252: 
                   15253: =item *
                   15254: 
1.243     albertel 15255: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15256: ($udom and $uname are optional)
1.191     harris41 15257: 
                   15258: =item *
                   15259: 
1.243     albertel 15260: cput($namespace,$storehash,$udom,$uname) : critical put
                   15261: ($udom and $uname are optional)
1.191     harris41 15262: 
                   15263: =item *
                   15264: 
1.748     albertel 15265: newput($namespace,$storehash,$udom,$uname) :
                   15266: 
                   15267: Attempts to store the items in the $storehash, but only if they don't
                   15268: currently exist, if this succeeds you can be certain that you have 
                   15269: successfully created a new key value pair in the $namespace db.
                   15270: 
                   15271: 
                   15272: Args:
                   15273:  $namespace: name of database to store values to
                   15274:  $storehash: hashref to store to the db
                   15275:  $udom: (optional) domain of user containing the db
                   15276:  $uname: (optional) name of user caontaining the db
                   15277: 
                   15278: Returns:
                   15279:  'ok' -> succeeded in storing all keys of $storehash
                   15280:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15281:                         least <key> already existed in the db (other
                   15282:                         requested keys may also already exist)
1.967     bisitz   15283:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15284:  'con_lost' -> unable to contact request server
                   15285:  'refused' -> action was not allowed by remote machine
                   15286: 
                   15287: 
                   15288: =item *
                   15289: 
1.243     albertel 15290: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15291: reference filled in from namesp (encrypts the return communication)
                   15292: ($udom and $uname are optional)
1.191     harris41 15293: 
                   15294: =item *
                   15295: 
1.243     albertel 15296: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15297: critical subroutine
                   15298: 
1.806     raeburn  15299: =item *
                   15300: 
1.860     raeburn  15301: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15302: array reference filled in from namespace found in domain level on either
                   15303: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15304: 
                   15305: =item *
                   15306: 
1.860     raeburn  15307: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15308: domain level either on specified domain server ($uhome) or primary domain 
                   15309: server ($udom and $uhome are optional)
1.806     raeburn  15310: 
1.943     raeburn  15311: =item * 
                   15312: 
1.1172.2.35  raeburn  15313: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15314: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15315: the target domain.
                   15316: 
                   15317: May also include additional key => value pairs for the following groups:
                   15318: 
                   15319: =over
                   15320: 
                   15321: =item
                   15322: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15323: 
                   15324: =over
                   15325: 
                   15326: =item defaultquota, authorquota
                   15327: 
                   15328: =back
                   15329: 
                   15330: =item
                   15331: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15332: portfolio for users).
                   15333: 
                   15334: =over
                   15335: 
                   15336: =item
                   15337: aboutme, blog, webdav, portfolio
                   15338: 
                   15339: =back
                   15340: 
                   15341: =item
                   15342: requestcourses: ability to request courses, and how requests are processed.
                   15343: 
                   15344: =over
                   15345: 
                   15346: =item
1.1172.2.37  raeburn  15347: official, unofficial, community, textbook
1.1172.2.35  raeburn  15348: 
                   15349: =back
                   15350: 
                   15351: =item
                   15352: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15353: 
                   15354: =over
                   15355: 
                   15356: =item
1.1172.2.44  raeburn  15357: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15358: 
                   15359: =back
                   15360: 
                   15361: =item
                   15362: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15363: for course's uploaded content.
                   15364: 
                   15365: =over
                   15366: 
                   15367: =item
1.1172.2.68  raeburn  15368: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15369: communityquota, textbookquota
1.1172.2.35  raeburn  15370: 
                   15371: =back
                   15372: 
                   15373: =item
                   15374: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15375: on your servers.
                   15376: 
                   15377: =over
                   15378: 
                   15379: =item
                   15380: remotesessions, hostedsessions
                   15381: 
                   15382: =back
                   15383: 
                   15384: =back
                   15385: 
                   15386: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15387: utility to create a configuration.db file on a domain's primary library server
                   15388: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15389: -- corresponding values are authentication type (internal, krb4, krb5,
                   15390: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15391: will be available. Values are retrieved from cache (if current), unless the
                   15392: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15393: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15394: 
                   15395: Typical usage:
1.943     raeburn  15396: 
1.1172.2.35  raeburn  15397: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15398: 
1.243     albertel 15399: =back
                   15400: 
                   15401: =head2 Network Status Functions
                   15402: 
                   15403: =over 4
1.191     harris41 15404: 
                   15405: =item *
                   15406: 
1.1137    raeburn  15407: dirlist() : return directory list based on URI (first arg).
                   15408: 
                   15409: Inputs: 1 required, 5 optional.
                   15410: 
                   15411: =over
                   15412: 
                   15413: =item 
                   15414: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15415: 
                   15416: =item
                   15417: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15418: 
                   15419: =item
                   15420: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15421: 
                   15422: =item
                   15423: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15424: 
                   15425: =item
                   15426: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15427: 
                   15428: =item 
                   15429: $alternateRoot - path to prepend in place of path from $uri.
                   15430: 
                   15431: =back
                   15432: 
                   15433: Returns: Array of up to two items.
                   15434: 
                   15435: =over
                   15436: 
                   15437: a reference to an array of files/subdirectories
                   15438: 
                   15439: =over
                   15440: 
                   15441: Each element in the array of files/subdirectories is a & separated list of
                   15442: item name and the result of running stat on the item.  If dirlist was requested
                   15443: for a file instead of a directory, the item name will be ''. For a directory 
                   15444: listing, if the item is a metadata file, the element will end &N&M 
                   15445: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15446: default copyright set (1).  
                   15447: 
                   15448: =back
                   15449: 
                   15450: a scalar containing error condition (if encountered).
                   15451: 
                   15452: =over
                   15453: 
                   15454: =item 
                   15455: no_host (no homeserver identified for $username:$domain).
                   15456: 
                   15457: =item 
                   15458: no_such_host (server contacted for listing not identified as valid host).
                   15459: 
                   15460: =item 
                   15461: con_lost (connection to remote server failed).
                   15462: 
                   15463: =item 
                   15464: refused (invalid $username:$domain received on lond side).
                   15465: 
                   15466: =item 
                   15467: no_such_dir (directory at specified path on lond side does not exist). 
                   15468: 
                   15469: =item 
                   15470: empty (directory at specified path on lond side is empty).
                   15471: 
                   15472: =over
                   15473: 
                   15474: This is currently not encountered because the &ls3, &ls2, 
                   15475: &ls (_handler) routines on the lond side do not filter out
                   15476: . and .. from a directory listing. 
                   15477: 
                   15478: =back
                   15479: 
                   15480: =back
                   15481: 
                   15482: =back
1.191     harris41 15483: 
                   15484: =item *
                   15485: 
1.243     albertel 15486: spareserver() : find server with least workload from spare.tab
                   15487: 
1.986     foxr     15488: 
                   15489: =item *
                   15490: 
                   15491: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15492: if there is no corresponding loncapa host.
                   15493: 
1.243     albertel 15494: =back
                   15495: 
1.986     foxr     15496: 
1.243     albertel 15497: =head2 Apache Request
                   15498: 
                   15499: =over 4
1.191     harris41 15500: 
                   15501: =item *
                   15502: 
1.243     albertel 15503: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15504: localhost, posts hash
                   15505: 
                   15506: =back
                   15507: 
                   15508: =head2 Data to String to Data
                   15509: 
                   15510: =over 4
1.191     harris41 15511: 
                   15512: =item *
                   15513: 
1.243     albertel 15514: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15515: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15516: 
                   15517: =item *
                   15518: 
1.243     albertel 15519: hashref2str($hashref) : convert a hashref into a string complete with
                   15520: escaping and '=' and '&' separators, supports elements that are
                   15521: arrayrefs and hashrefs
1.191     harris41 15522: 
                   15523: =item *
                   15524: 
1.243     albertel 15525: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15526: with escaping and '&' separators, supports elements that are arrayrefs
                   15527: and hashrefs
1.191     harris41 15528: 
                   15529: =item *
                   15530: 
1.243     albertel 15531: str2hash($string) : convert string to hash using unescaping and
                   15532: splitting on '=' and '&', supports elements that are arrayrefs and
                   15533: hashrefs
1.191     harris41 15534: 
                   15535: =item *
                   15536: 
1.243     albertel 15537: str2array($string) : convert string to hash using unescaping and
                   15538: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15539: 
                   15540: =back
                   15541: 
                   15542: =head2 Logging Routines
                   15543: 
                   15544: 
                   15545: These routines allow one to make log messages in the lonnet.log and
                   15546: lonnet.perm logfiles.
1.191     harris41 15547: 
1.1119    foxr     15548: =over 4
                   15549: 
1.191     harris41 15550: =item *
                   15551: 
1.243     albertel 15552: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15553: 
                   15554: =item *
                   15555: 
1.243     albertel 15556: logthis() : append message to the normal lonnet.log file, it gets
                   15557: preiodically rolled over and deleted.
1.191     harris41 15558: 
                   15559: =item *
                   15560: 
1.243     albertel 15561: logperm() : append a permanent message to lonnet.perm.log, this log
                   15562: file never gets deleted by any automated portion of the system, only
                   15563: messages of critical importance should go in here.
                   15564: 
1.1119    foxr     15565: 
1.243     albertel 15566: =back
                   15567: 
                   15568: =head2 General File Helper Routines
                   15569: 
                   15570: =over 4
1.191     harris41 15571: 
                   15572: =item *
                   15573: 
1.481     raeburn  15574: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15575: (a) files in /uploaded
                   15576:   (i) If a local copy of the file exists - 
                   15577:       compares modification date of local copy with last-modified date for 
                   15578:       definitive version stored on home server for course. If local copy is 
                   15579:       stale, requests a new version from the home server and stores it. 
                   15580:       If the original has been removed from the home server, then local copy 
                   15581:       is unlinked.
                   15582:   (ii) If local copy does not exist -
                   15583:       requests the file from the home server and stores it. 
                   15584:   
                   15585:   If $caller is 'uploadrep':  
                   15586:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15587:     for request for files originally uploaded via DOCS. 
                   15588:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15589:   
                   15590:   Otherwise:
                   15591:      This indicates a call from the content generation phase of the request.
                   15592:      -  returns the entire contents of the file or -1.
                   15593:      
                   15594: (b) files in /res
                   15595:    - returns the entire contents of a file or -1; 
                   15596:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15597: 
1.712     albertel 15598: 
                   15599: =item *
                   15600: 
                   15601: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15602:                   reference
                   15603: 
                   15604: returns either a stat() list of data about the file or an empty list
                   15605: if the file doesn't exist or couldn't find out about it (connection
                   15606: problems or user unknown)
                   15607: 
1.191     harris41 15608: =item *
                   15609: 
1.243     albertel 15610: filelocation($dir,$file) : returns file system location of a file
                   15611: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15612: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15613: and a file of ../bob will become /a/bob)
1.191     harris41 15614: 
                   15615: =item *
                   15616: 
                   15617: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15618: filelocation except for hrefs
                   15619: 
                   15620: =item *
                   15621: 
1.1172.2.49  raeburn  15622: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15623: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15624: 
1.243     albertel 15625: =back
                   15626: 
1.608     albertel 15627: =head2 Usererfile file routines (/uploaded*)
                   15628: 
                   15629: =over 4
                   15630: 
                   15631: =item *
                   15632: 
                   15633: userfileupload(): main rotine for putting a file in a user or course's
                   15634:                   filespace, arguments are,
                   15635: 
1.620     albertel 15636:  formname - required - this is the name of the element in $env where the
1.608     albertel 15637:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15638:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15639:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15640:  context - if coursedoc, store the file in the course of the active role
                   15641:              of the current user; 
                   15642:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15643:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15644:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15645:          if undefined, it will be placed in "unknown"
                   15646: 
                   15647:  (This routine calls clean_filename() to remove any dangerous
                   15648:  characters from the filename, and then calls finuserfileupload() to
                   15649:  complete the transaction)
                   15650: 
                   15651:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15652:  and /adm/notfound.html if unsuccessful
                   15653: 
                   15654: =item *
                   15655: 
                   15656: clean_filename(): routine for cleaing a filename up for storage in
                   15657:                  userfile space, argument is:
                   15658: 
                   15659:  filename - proposed filename
                   15660: 
                   15661: returns: the new clean filename
                   15662: 
                   15663: =item *
                   15664: 
1.1090    raeburn  15665: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15666: userspace, probably shouldn't be called directly
                   15667: 
                   15668:   docuname: username or courseid of destination for the file
                   15669:   docudom: domain of user/course of destination for the file
                   15670:   formname: same as for userfileupload()
1.1090    raeburn  15671:   fname: filename (including subdirectories) for the file
                   15672:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15673:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15674:   allfiles: reference to hash used to store objects found by parser
                   15675:   codebase: reference to hash used for codebases of java objects found by parser
                   15676:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15677:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15678:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15679:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15680:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15681:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15682:   mimetype: reference to scalar to accommodate mime type determined
                   15683:             from File::MMagic if $parser = parse.
1.608     albertel 15684: 
                   15685:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15686:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15687:  was 'overwrite').
                   15688:  
1.608     albertel 15689: 
                   15690: =item *
                   15691: 
                   15692: renameuserfile(): renames an existing userfile to a new name
                   15693: 
                   15694:   Args:
                   15695:    docuname: username or courseid of destination for the file
                   15696:    docudom: domain of user/course of destination for the file
                   15697:    old: current file name (including any subdirs under userfiles)
                   15698:    new: desired file name (including any subdirs under userfiles)
                   15699: 
                   15700: =item *
                   15701: 
                   15702: mkdiruserfile(): creates a directory is a userfiles dir
                   15703: 
                   15704:   Args:
                   15705:    docuname: username or courseid of destination for the file
                   15706:    docudom: domain of user/course of destination for the file
                   15707:    dir: dir to create (including any subdirs under userfiles)
                   15708: 
                   15709: =item *
                   15710: 
                   15711: removeuserfile(): removes a file that exists in userfiles
                   15712: 
                   15713:   Args:
                   15714:    docuname: username or courseid of destination for the file
                   15715:    docudom: domain of user/course of destination for the file
                   15716:    fname: filname to delete (including any subdirs under userfiles)
                   15717: 
                   15718: =item *
                   15719: 
                   15720: removeuploadedurl(): convience function for removeuserfile()
                   15721: 
                   15722:   Args:
                   15723:    url:  a full /uploaded/... url to delete
                   15724: 
1.747     albertel 15725: =item * 
                   15726: 
                   15727: get_portfile_permissions():
                   15728:   Args:
                   15729:     domain: domain of user or course contain the portfolio files
                   15730:     user: name of user or num of course contain the portfolio files
                   15731:   Returns:
                   15732:     hashref of a dump of the proper file_permissions.db
                   15733:    
                   15734: 
                   15735: =item * 
                   15736: 
                   15737: get_access_controls():
                   15738: 
                   15739: Args:
                   15740:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15741:   group: (optional) the group you want the files associated with
                   15742:   file: (optional) the file you want access info on
                   15743: 
                   15744: Returns:
1.749     raeburn  15745:     a hash (keys are file names) of hashes containing
                   15746:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15747:         values are XML containing access control settings (see below) 
1.747     albertel 15748: 
                   15749: Internal notes:
                   15750: 
1.749     raeburn  15751:  access controls are stored in file_permissions.db as key=value pairs.
                   15752:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15753:         where scope -> public,guest,course,group,domains or users.
                   15754:               end -> UNIX time for end of access (0 -> no end date)
                   15755:               start -> UNIX time for start of access
                   15756: 
                   15757:     value -> XML description of access control
                   15758:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15759:             <start></start>
                   15760:             <end></end>
                   15761: 
                   15762:             <password></password>  for scope type = guest
                   15763: 
                   15764:             <domain></domain>     for scope type = course or group
                   15765:             <number></number>
                   15766:             <roles id="">
                   15767:              <role></role>
                   15768:              <access></access>
                   15769:              <section></section>
                   15770:              <group></group>
                   15771:             </roles>
                   15772: 
                   15773:             <dom></dom>         for scope type = domains
                   15774: 
                   15775:             <users>             for scope type = users
                   15776:              <user>
                   15777:               <uname></uname>
                   15778:               <udom></udom>
                   15779:              </user>
                   15780:             </users>
                   15781:            </scope> 
                   15782:               
                   15783:  Access data is also aggregated for each file in an additional key=value pair:
                   15784:  key -> path to file/file_name\0accesscontrol 
                   15785:  value -> reference to hash
                   15786:           hash contains key = value pairs
                   15787:           where key = uniqueID:scope_end_start
                   15788:                 value = UNIX time record was last updated
                   15789: 
                   15790:           Used to improve speed of look-ups of access controls for each file.  
                   15791:  
                   15792:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15793: 
1.1172.2.13  raeburn  15794: =item *
                   15795: 
1.749     raeburn  15796: modify_access_controls():
                   15797: 
                   15798: Modifies access controls for a portfolio file
                   15799: Args
                   15800: 1. file name
                   15801: 2. reference to hash of required changes,
                   15802: 3. domain
                   15803: 4. username
                   15804:   where domain,username are the domain of the portfolio owner 
                   15805:   (either a user or a course) 
                   15806: 
                   15807: Returns:
                   15808: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15809: 2. result of deletions ('ok' or 'error', with error message).
                   15810: 3. reference to hash of any new or updated access controls.
                   15811: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15812:    key = integer (inbound ID)
1.1172.2.13  raeburn  15813:    value = uniqueID
                   15814: 
                   15815: =item *
                   15816: 
                   15817: get_timebased_id():
                   15818: 
                   15819: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15820: course via the Course Editor (e.g., folders, composite pages,
                   15821: group bulletin boards).
                   15822: 
                   15823: Args: (first three required; six others optional)
                   15824: 
                   15825: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15826:    docssequence, or name of group
                   15827: 
                   15828: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15829:    e.g., num, boardids
                   15830: 
                   15831: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15832:    file will be named nohist_namespace.db
                   15833: 
                   15834: 4. cdom: domain of course; default is current course domain from %env
                   15835: 
                   15836: 5. cnum: course number; default is current course number from %env
                   15837: 
                   15838: 6. idtype: set to concat if an additional digit is to be appended to the
                   15839:    unix timestamp to form the suffix, if the plain timestamp is already
                   15840:    in use.  Default is to not do this, but simply increment the unix
                   15841:    timestamp by 1 until a unique key is obtained.
                   15842: 
                   15843: 7. who: holder of locking key; defaults to user:domain for user.
                   15844: 
                   15845: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15846:    retrying); default is 3.
                   15847: 
                   15848: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15849: 
                   15850: Returns:
                   15851: 
                   15852: 1. suffix obtained (numeric)
                   15853: 
                   15854: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15855: 
                   15856: 3. error: contains (localized) error message if an error occurred.
                   15857: 
1.747     albertel 15858: 
1.608     albertel 15859: =back
                   15860: 
1.243     albertel 15861: =head2 HTTP Helper Routines
                   15862: 
                   15863: =over 4
                   15864: 
1.191     harris41 15865: =item *
                   15866: 
                   15867: escape() : unpack non-word characters into CGI-compatible hex codes
                   15868: 
                   15869: =item *
                   15870: 
                   15871: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15872: 
1.243     albertel 15873: =back
                   15874: 
                   15875: =head1 PRIVATE SUBROUTINES
                   15876: 
                   15877: =head2 Underlying communication routines (Shouldn't call)
                   15878: 
                   15879: =over 4
                   15880: 
                   15881: =item *
                   15882: 
                   15883: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15884: 
                   15885: =item *
                   15886: 
                   15887: reply() : uses subreply to send a message to remote machine, logs all failures
                   15888: 
                   15889: =item *
                   15890: 
                   15891: critical() : passes a critical message to another server; if cannot
                   15892: get through then place message in connection buffer directory and
                   15893: returns con_delayed, if incapable of saving message, returns
                   15894: con_failed
                   15895: 
                   15896: =item *
                   15897: 
                   15898: reconlonc() : tries to reconnect lonc client processes.
                   15899: 
                   15900: =back
                   15901: 
                   15902: =head2 Resource Access Logging
                   15903: 
                   15904: =over 4
                   15905: 
                   15906: =item *
                   15907: 
                   15908: flushcourselogs() : flush (save) buffer logs and access logs
                   15909: 
                   15910: =item *
                   15911: 
                   15912: courselog($what) : save message for course in hash
                   15913: 
                   15914: =item *
                   15915: 
                   15916: courseacclog($what) : save message for course using &courselog().  Perform
                   15917: special processing for specific resource types (problems, exams, quizzes, etc).
                   15918: 
1.191     harris41 15919: =item *
                   15920: 
                   15921: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15922: as a PerlChildExitHandler
1.243     albertel 15923: 
                   15924: =back
                   15925: 
                   15926: =head2 Other
                   15927: 
                   15928: =over 4
                   15929: 
                   15930: =item *
                   15931: 
                   15932: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15933: 
                   15934: =back
                   15935: 
                   15936: =cut
1.877     foxr     15937: 

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