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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.132! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.131 2020/11/24 15:03:06 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.120  raeburn   266:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   269:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.120  raeburn   960:                 my $protocol = 'http';
                    961:                 if ($protocol{$spare_server} eq 'https') {
                    962:                     $protocol = $protocol{$spare_server};
                    963:                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
1.1172.2.130  raeburn  1085: sub updatebalcookie {
                   1086:     my ($cookie,$balancer,$lastentry)=@_;
                   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('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1095:         }
                   1096:     }
                   1097:     return;
                   1098: }
                   1099: 
1.1172.2.107  raeburn  1100: sub delbalcookie {
                   1101:     my ($cookie,$balancer) =@_;
                   1102:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1103:         my ($udom,$uname) = ($1,$2);
                   1104:         my $uprimary_id = &domain($udom,'primary');
                   1105:         my $uintdom = &internet_dom($uprimary_id);
                   1106:         my $intdom = &internet_dom($balancer);
                   1107:         my $serverhomedom = &host_domain($balancer);
                   1108:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1109:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1110:         }
                   1111:     }
                   1112: }
                   1113: 
1.914     albertel 1114: # -------------------------------- ask if server already has a session for user
                   1115: sub has_user_session {
                   1116:     my ($lonid,$udom,$uname) = @_;
                   1117:     my $result = &reply(join(':','userhassession',
                   1118: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1119:     return 1 if ($result eq 'ok');
                   1120: 
                   1121:     return 0;
                   1122: }
                   1123: 
1.1076    raeburn  1124: # --------- determine least loaded server in a user's domain which allows login
                   1125: 
                   1126: sub choose_server {
1.1172.2.47  raeburn  1127:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1128:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1129:     my %servers = &get_servers($udom);
1.1076    raeburn  1130:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1131:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1132:     if ($skiploadbal) {
                   1133:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1134:         unless (defined($cached)) {
                   1135:             my $cachetime = 60*60*24;
                   1136:             my %domconfig =
                   1137:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1138:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1139:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1140:                                            $cachetime);
                   1141:             }
                   1142:         }
                   1143:     }
1.1076    raeburn  1144:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1145:         my $loginvia;
1.1172.2.47  raeburn  1146:         if ($skiploadbal) {
                   1147:             if (ref($balancers) eq 'HASH') {
                   1148:                 next if (exists($balancers->{$lonhost}));
                   1149:             }
                   1150:         }
1.1115    raeburn  1151:         if ($checkloginvia) {
                   1152:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1153:             if ($loginvia) {
                   1154:                 my ($server,$path) = split(/:/,$loginvia);
                   1155:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1157:                 if ($login_host eq $server) {
                   1158:                     $portal_path = $path;
1.1151    raeburn  1159:                     $isredirect = 1;
1.1116    raeburn  1160:                 }
                   1161:             } else {
                   1162:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1163:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1164:                 if ($login_host eq $lonhost) {
                   1165:                     $portal_path = '';
1.1151    raeburn  1166:                     $isredirect = ''; 
1.1116    raeburn  1167:                 }
                   1168:             }
                   1169:         } else {
1.1076    raeburn  1170:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1171:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1172:         }
                   1173:     }
                   1174:     if ($login_host ne '') {
1.1116    raeburn  1175:         $hostname = &hostname($login_host);
1.1076    raeburn  1176:     }
1.1172.2.88  raeburn  1177:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1178: }
                   1179: 
1.1172.2.123  raeburn  1180: sub get_course_sessions {
                   1181:     my ($cnum,$cdom,$lastactivity) = @_;
                   1182:     my %servers = &internet_dom_servers($cdom);
                   1183:     my %returnhash;
                   1184:     foreach my $server (sort(keys(%servers))) {
                   1185:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1186:         my @pairs=split(/\&/,$rep);
                   1187:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1188:             foreach my $item (@pairs) {
                   1189:                 my ($key,$value)=split(/=/,$item,2);
                   1190:                 $key = &unescape($key);
                   1191:                 next if ($key =~ /^error: 2 /);
                   1192:                 if (exists($returnhash{$key})) {
                   1193:                     next if ($value < $returnhash{$key});
                   1194:                 }
                   1195:                 $returnhash{$key}=$value;
                   1196:             }
                   1197:         }
                   1198:     }
                   1199:     return %returnhash;
                   1200: }
                   1201: 
1.202     matthew  1202: # --------------------------------------------- Try to change a user's password
                   1203: 
                   1204: sub changepass {
1.799     raeburn  1205:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1206:     $currentpass = &escape($currentpass);
                   1207:     $newpass     = &escape($newpass);
1.1030    raeburn  1208:     my $lonhost = $perlvar{'lonHostID'};
                   1209:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1210: 		       $server);
                   1211:     if (! $answer) {
                   1212: 	&logthis("No reply on password change request to $server ".
                   1213: 		 "by $uname in domain $udom.");
                   1214:     } elsif ($answer =~ "^ok") {
                   1215:         &logthis("$uname in $udom successfully changed their password ".
                   1216: 		 "on $server.");
                   1217:     } elsif ($answer =~ "^pwchange_failure") {
                   1218: 	&logthis("$uname in $udom was unable to change their password ".
                   1219: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1220: 		 "or pwchange");
                   1221:     } elsif ($answer =~ "^non_authorized") {
                   1222:         &logthis("$uname in $udom did not get their password correct when ".
                   1223: 		 "attempting to change it on $server.");
                   1224:     } elsif ($answer =~ "^auth_mode_error") {
                   1225:         &logthis("$uname in $udom attempted to change their password despite ".
                   1226: 		 "not being locally or internally authenticated on $server.");
                   1227:     } elsif ($answer =~ "^unknown_user") {
                   1228:         &logthis("$uname in $udom attempted to change their password ".
                   1229: 		 "on $server but were unable to because $server is not ".
                   1230: 		 "their home server.");
                   1231:     } elsif ($answer =~ "^refused") {
                   1232: 	&logthis("$server refused to change $uname in $udom password because ".
                   1233: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1234:     } elsif ($answer =~ "invalid_client") {
                   1235:         &logthis("$server refused to change $uname in $udom password because ".
                   1236:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1237:     } elsif ($answer =~ "^prioruse") {
                   1238:        &logthis("$server refused to change $uname in $udom password because ".
                   1239:                 "the password had been used before");
1.202     matthew  1240:     }
                   1241:     return $answer;
1.1       albertel 1242: }
                   1243: 
1.169     harris41 1244: # ----------------------- Try to determine user's current authentication scheme
                   1245: 
                   1246: sub queryauthenticate {
                   1247:     my ($uname,$udom)=@_;
1.456     albertel 1248:     my $uhome=&homeserver($uname,$udom);
                   1249:     if (!$uhome) {
                   1250: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1251: 	return 'no_host';
                   1252:     }
                   1253:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1254:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1255: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1256:     }
1.456     albertel 1257:     return $answer;
1.169     harris41 1258: }
                   1259: 
1.1       albertel 1260: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1261: 
1.1       albertel 1262: sub authenticate {
1.1073    raeburn  1263:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1264:     $upass=&escape($upass);
                   1265:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1266:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1267:     my $newhome;
1.836     www      1268:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1269: # Maybe the machine was offline and only re-appeared again recently?
                   1270:         &reconlonc();
                   1271: # One more
1.952     raeburn  1272: 	$uhome=&homeserver($uname,$udom,1);
                   1273:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1274:             if (defined(&domain($udom,'primary'))) {
                   1275:                 $newhome=&domain($udom,'primary');
                   1276:             }
                   1277:             if ($newhome ne '') {
                   1278:                 $uhome = $newhome;
                   1279:             }
                   1280:         }
1.836     www      1281: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1282: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1283: 	    return 'no_host';
                   1284:         }
1.1       albertel 1285:     }
1.1073    raeburn  1286:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1287:     if ($answer eq 'authorized') {
1.952     raeburn  1288:         if ($newhome) {
                   1289:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1290:             return 'no_account_on_host'; 
                   1291:         } else {
                   1292:             &logthis("User $uname at $udom authorized by $uhome");
                   1293:             return $uhome;
                   1294:         }
1.471     albertel 1295:     }
                   1296:     if ($answer eq 'non_authorized') {
                   1297: 	&logthis("User $uname at $udom rejected by $uhome");
                   1298: 	return 'no_host'; 
1.9       www      1299:     }
1.471     albertel 1300:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1301:     return 'no_host';
                   1302: }
                   1303: 
1.1073    raeburn  1304: sub can_host_session {
1.1074    raeburn  1305:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1306:     my $canhost = 1;
1.1074    raeburn  1307:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1308:     if (ref($remotesessions) eq 'HASH') {
                   1309:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1311:                 $canhost = 0;
                   1312:             } else {
                   1313:                 $canhost = 1;
                   1314:             }
                   1315:         }
                   1316:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1317:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1318:                 $canhost = 1;
                   1319:             } else {
                   1320:                 $canhost = 0;
                   1321:             }
                   1322:         }
                   1323:         if ($canhost) {
                   1324:             if ($remotesessions->{'version'} ne '') {
                   1325:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1326:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1327:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1328:                         my $major = $1;
                   1329:                         my $minor = $2;
                   1330:                         if (($major < $reqmajor ) ||
                   1331:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1332:                             $canhost = 0;
                   1333:                         }
                   1334:                     } else {
                   1335:                         $canhost = 0;
                   1336:                     }
                   1337:                 }
                   1338:             }
                   1339:         }
                   1340:     }
                   1341:     if ($canhost) {
                   1342:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1343:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1344:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1345:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1346:                 if (($uint_dom ne '') && 
                   1347:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1348:                     $canhost = 0;
                   1349:                 } else {
                   1350:                     $canhost = 1;
                   1351:                 }
                   1352:             }
                   1353:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1354:                 if (($uint_dom ne '') && 
                   1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1356:                     $canhost = 1;
                   1357:                 } else {
                   1358:                     $canhost = 0;
                   1359:                 }
                   1360:             }
                   1361:         }
                   1362:     }
                   1363:     return $canhost;
                   1364: }
                   1365: 
1.1083    raeburn  1366: sub spare_can_host {
                   1367:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1368:     my $canhost=1;
1.1172.2.62  raeburn  1369:     my $try_server_hostname = &hostname($try_server);
                   1370:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1371:     my $serverhomedom = &host_domain($serverhomeID);
                   1372:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1373:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1374:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1375:             $canhost = 0;
                   1376:         }
                   1377:     }
                   1378:     if (($canhost) && ($uint_dom)) {
                   1379:         my @intdoms;
                   1380:         my $internet_names = &get_internet_names($try_server);
                   1381:         if (ref($internet_names) eq 'ARRAY') {
                   1382:             @intdoms = @{$internet_names};
                   1383:         }
                   1384:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1385:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1386:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1387:                                          $remotesessions,
                   1388:                                          $defdomdefaults{'hostedsessions'});
                   1389:         }
1.1083    raeburn  1390:     }
                   1391:     return $canhost;
                   1392: }
                   1393: 
1.1123    raeburn  1394: sub this_host_spares {
                   1395:     my ($dom) = @_;
1.1126    raeburn  1396:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1397:     my @hosts = &current_machine_ids();
                   1398:     foreach my $lonhost (@hosts) {
                   1399:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1400:             $dom_in_use = $dom;
                   1401:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1402:             last;
                   1403:         }
                   1404:     }
1.1126    raeburn  1405:     if ($dom_in_use ne '') {
                   1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1407:     }
                   1408:     if (ref($result) ne 'HASH') {
                   1409:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1410:         $dom_in_use = &host_domain($lonhost_in_use);
                   1411:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1412:         if (ref($result) ne 'HASH') {
                   1413:             $result = \%spareid;
                   1414:         }
                   1415:     }
                   1416:     return $result;
                   1417: }
                   1418: 
                   1419: sub spares_for_offload  {
                   1420:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1421:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1422:     if (defined($cached)) {
                   1423:         return $result;
                   1424:     } else {
1.1126    raeburn  1425:         my $cachetime = 60*60*24;
                   1426:         my %domconfig =
                   1427:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1428:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1429:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1430:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1431:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1432:                 }
                   1433:             }
                   1434:         }
                   1435:     }
1.1126    raeburn  1436:     return;
1.1123    raeburn  1437: }
                   1438: 
1.1129    raeburn  1439: sub get_lonbalancer_config {
                   1440:     my ($servers) = @_;
                   1441:     my ($currbalancer,$currtargets);
                   1442:     if (ref($servers) eq 'HASH') {
                   1443:         foreach my $server (keys(%{$servers})) {
                   1444:             my %what = (
                   1445:                          spareid => 1,
                   1446:                          perlvar => 1,
                   1447:                        );
                   1448:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1449:             if ($result eq 'ok') {
                   1450:                 if (ref($returnhash) eq 'HASH') {
                   1451:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1452:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1453:                             $currbalancer = $server;
                   1454:                             $currtargets = {};
                   1455:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1456:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1457:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1458:                                 }
                   1459:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1460:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1461:                                 }
                   1462:                             }
                   1463:                             last;
                   1464:                         }
                   1465:                     }
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($currbalancer,$currtargets);
                   1471: }
                   1472: 
                   1473: sub check_loadbalancing {
1.1172.2.88  raeburn  1474:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1475:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1476:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1477:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1478:     my @hosts = &current_machine_ids();
1.1129    raeburn  1479:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1480:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1481:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1482:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1483:     my $domneedscache; 
1.1129    raeburn  1484:     my $cachetime = 60*60*24;
                   1485: 
                   1486:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1487:         $dom_in_use = $udom;
                   1488:         $homeintdom = 1;
                   1489:     } else {
                   1490:         $dom_in_use = $serverhomedom;
                   1491:     }
                   1492:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1493:     unless (defined($cached)) {
                   1494:         my %domconfig =
                   1495:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1496:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1497:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1498:         } else {
                   1499:             $domneedscache = $dom_in_use;
1.1129    raeburn  1500:         }
                   1501:     }
                   1502:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1503:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1504:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1505:         if ($is_balancer) {
                   1506:             if (ref($currrules) eq 'HASH') {
                   1507:                 if ($homeintdom) {
                   1508:                     if ($uname ne '') {
                   1509:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1510:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1511:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1512:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1513:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1514:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1515:                             }
                   1516:                         }
                   1517:                         if ($rule_in_effect eq '') {
                   1518:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1519:                             if ($userenv{'inststatus'} ne '') {
                   1520:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1521:                                 my ($othertitle,$usertypes,$types) =
                   1522:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1523:                                 if (ref($types) eq 'ARRAY') {
                   1524:                                     foreach my $type (@{$types}) {
                   1525:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1526:                                             if (exists($currrules->{$type})) {
                   1527:                                                 $rule_in_effect = $currrules->{$type};
                   1528:                                             }
                   1529:                                         }
                   1530:                                     }
                   1531:                                 }
                   1532:                             } else {
                   1533:                                 if (exists($currrules->{'default'})) {
                   1534:                                     $rule_in_effect = $currrules->{'default'};
                   1535:                                 }
                   1536:                             }
                   1537:                         }
                   1538:                     } else {
                   1539:                         if (exists($currrules->{'default'})) {
                   1540:                             $rule_in_effect = $currrules->{'default'};
                   1541:                         }
                   1542:                     }
                   1543:                 } else {
                   1544:                     if ($currrules->{'_LC_external'} ne '') {
                   1545:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1546:                     }
                   1547:                 }
                   1548:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1549:                                                        $uname,$udom);
                   1550:             }
                   1551:         }
                   1552:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1553:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1554:         unless (defined($cached)) {
                   1555:             my %domconfig =
                   1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1558:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1559:             } else {
                   1560:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1561:             }
                   1562:         }
                   1563:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1564:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1565:                 &check_balancer_result($result,@hosts);
                   1566:             if ($is_balancer) {
1.1129    raeburn  1567:                 if (ref($currrules) eq 'HASH') {
                   1568:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1569:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1570:                     }
                   1571:                 }
                   1572:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1573:                                                        $uname,$udom);
                   1574:             }
                   1575:         } else {
                   1576:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1577:                 $is_balancer = 1;
                   1578:                 $offloadto = &this_host_spares($dom_in_use);
                   1579:             }
1.1172.2.75  raeburn  1580:             unless (defined($cached)) {
                   1581:                 $domneedscache = $serverhomedom;
                   1582:             }
1.1129    raeburn  1583:         }
                   1584:     } else {
                   1585:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1586:             $is_balancer = 1;
                   1587:             $offloadto = &this_host_spares($dom_in_use);
                   1588:         }
1.1172.2.75  raeburn  1589:         unless (defined($cached)) {
                   1590:             $domneedscache = $serverhomedom;
                   1591:         }
                   1592:     }
                   1593:     if ($domneedscache) {
                   1594:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1595:     }
1.1172.2.130  raeburn  1596:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1597:         my $lowest_load = 30000;
                   1598:         if (ref($offloadto) eq 'HASH') {
                   1599:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1600:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1601:                     ($otherserver,$lowest_load) =
                   1602:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1603:                 }
1.1129    raeburn  1604:             }
1.1172.2.5  raeburn  1605:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1606: 
1.1172.2.5  raeburn  1607:             if (!$found_server) {
                   1608:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1609:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1610:                         ($otherserver,$lowest_load) =
                   1611:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1612:                     }
                   1613:                 }
                   1614:             }
                   1615:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1616:             if (@{$offloadto} == 1) {
                   1617:                 $otherserver = $offloadto->[0];
                   1618:             } elsif (@{$offloadto} > 1) {
                   1619:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1620:                     ($otherserver,$lowest_load) =
                   1621:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                 }
                   1623:             }
                   1624:         }
1.1172.2.88  raeburn  1625:         unless ($caller eq 'login') {
                   1626:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1627:                 $is_balancer = 0;
                   1628:                 if ($uname ne '' && $udom ne '') {
                   1629:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1630:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1631:                                  'user.loadbalcheck.time' => time});
                   1632:                     }
1.1172.2.5  raeburn  1633:                 }
1.1129    raeburn  1634:             }
                   1635:         }
1.1172.2.130  raeburn  1636:     }
                   1637:     if (($is_balancer) && (!$homeintdom)) {
                   1638:         undef($setcookie);
1.1129    raeburn  1639:     }
1.1172.2.107  raeburn  1640:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1641: }
                   1642: 
1.1172.2.12  raeburn  1643: sub check_balancer_result {
                   1644:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1645:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1646:     if (ref($result) eq 'HASH') {
                   1647:         if ($result->{'lonhost'} ne '') {
                   1648:             my $currbalancer = $result->{'lonhost'};
                   1649:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1650:                 $is_balancer = 1;
                   1651:                 $currtargets = $result->{'targets'};
                   1652:                 $currrules = $result->{'rules'};
                   1653:             }
                   1654:         } else {
                   1655:             foreach my $key (keys(%{$result})) {
                   1656:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1657:                     (ref($result->{$key}) eq 'HASH')) {
                   1658:                     $is_balancer = 1;
                   1659:                     $currrules = $result->{$key}{'rules'};
                   1660:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1661:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1662:                     last;
                   1663:                 }
                   1664:             }
                   1665:         }
                   1666:     }
1.1172.2.107  raeburn  1667:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1668: }
                   1669: 
1.1129    raeburn  1670: sub get_loadbalancer_targets {
                   1671:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1672:     my $offloadto;
1.1172.2.4  raeburn  1673:     if ($rule_in_effect eq 'none') {
                   1674:         return [$perlvar{'lonHostID'}];
                   1675:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1676:         $offloadto = $currtargets;
                   1677:     } else {
                   1678:         if ($rule_in_effect eq 'homeserver') {
                   1679:             my $homeserver = &homeserver($uname,$udom);
                   1680:             if ($homeserver ne 'no_host') {
                   1681:                 $offloadto = [$homeserver];
                   1682:             }
                   1683:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1684:             my %domconfig =
                   1685:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1686:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1687:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1688:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1689:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1690:                     }
                   1691:                 }
                   1692:             } else {
1.1172.2.7  raeburn  1693:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1694:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1695:                 if (&hostname($remotebalancer) ne '') {
                   1696:                     $offloadto = [$remotebalancer];
                   1697:                 }
                   1698:             }
                   1699:         } elsif (&hostname($rule_in_effect) ne '') {
                   1700:             $offloadto = [$rule_in_effect];
                   1701:         }
                   1702:     }
                   1703:     return $offloadto;
                   1704: }
                   1705: 
1.1127    raeburn  1706: sub internet_dom_servers {
                   1707:     my ($dom) = @_;
                   1708:     my (%uniqservers,%servers);
                   1709:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1710:     my @machinedoms = &machine_domains($primaryserver);
                   1711:     foreach my $mdom (@machinedoms) {
                   1712:         my %currservers = %servers;
                   1713:         my %server = &get_servers($mdom);
                   1714:         %servers = (%currservers,%server);
                   1715:     }
                   1716:     my %by_hostname;
                   1717:     foreach my $id (keys(%servers)) {
                   1718:         push(@{$by_hostname{$servers{$id}}},$id);
                   1719:     }
                   1720:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1721:         if (@{$by_hostname{$hostname}} > 1) {
                   1722:             my $match = 0;
                   1723:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1724:                 if (&host_domain($id) eq $dom) {
                   1725:                     $uniqservers{$id} = $hostname;
                   1726:                     $match = 1;
                   1727:                 }
                   1728:             }
                   1729:             unless ($match) {
                   1730:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1731:             }
                   1732:         } else {
                   1733:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1734:         }
                   1735:     }
                   1736:     return %uniqservers;
                   1737: }
                   1738: 
1.1       albertel 1739: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1740: 
1.599     albertel 1741: my %homecache;
1.1       albertel 1742: sub homeserver {
1.230     stredwic 1743:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1744:     my $index="$uname:$udom";
1.426     albertel 1745: 
1.599     albertel 1746:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1747: 
                   1748:     my %servers = &get_servers($udom,'library');
                   1749:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1750:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1751: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1752: 
                   1753: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1754: 	if ($answer eq 'found') {
                   1755: 	    delete($badServerCache{$tryserver}); 
                   1756: 	    return $homecache{$index}=$tryserver;
                   1757: 	} elsif ($answer eq 'no_host') {
                   1758: 	    $badServerCache{$tryserver}=1;
                   1759: 	}
1.1       albertel 1760:     }    
                   1761:     return 'no_host';
1.70      www      1762: }
                   1763: 
                   1764: # ------------------------------------- Find the usernames behind a list of IDs
                   1765: 
                   1766: sub idget {
                   1767:     my ($udom,@ids)=@_;
                   1768:     my %returnhash=();
                   1769:     
1.841     albertel 1770:     my %servers = &get_servers($udom,'library');
                   1771:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1772: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1773: 	$idlist=~tr/A-Z/a-z/; 
                   1774: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1775: 	my @answer=();
                   1776: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1777: 	    @answer=split(/\&/,$reply);
                   1778: 	}                    ;
                   1779: 	my $i;
                   1780: 	for ($i=0;$i<=$#ids;$i++) {
                   1781: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1782: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1783: 	    } 
                   1784: 	}
                   1785:     } 
1.70      www      1786:     return %returnhash;
                   1787: }
                   1788: 
                   1789: # ------------------------------------- Find the IDs behind a list of usernames
                   1790: 
                   1791: sub idrget {
                   1792:     my ($udom,@unames)=@_;
                   1793:     my %returnhash=();
1.800     albertel 1794:     foreach my $uname (@unames) {
                   1795:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1796:     }
1.70      www      1797:     return %returnhash;
                   1798: }
                   1799: 
                   1800: # ------------------------------- Store away a list of names and associated IDs
                   1801: 
                   1802: sub idput {
                   1803:     my ($udom,%ids)=@_;
                   1804:     my %servers=();
1.800     albertel 1805:     foreach my $uname (keys(%ids)) {
                   1806: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1807:         my $uhom=&homeserver($uname,$udom);
1.70      www      1808:         if ($uhom ne 'no_host') {
1.800     albertel 1809:             my $id=&escape($ids{$uname});
1.70      www      1810:             $id=~tr/A-Z/a-z/;
1.800     albertel 1811:             my $esc_unam=&escape($uname);
1.70      www      1812: 	    if ($servers{$uhom}) {
1.800     albertel 1813: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1814:             } else {
1.800     albertel 1815:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1816:             }
                   1817:         }
1.191     harris41 1818:     }
1.800     albertel 1819:     foreach my $server (keys(%servers)) {
                   1820:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1821:     }
1.344     www      1822: }
                   1823: 
1.1172.2.30  raeburn  1824: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1825: 
                   1826: sub iddel {
                   1827:     my ($udom,$idshashref,$uhome)=@_;
                   1828:     my %result=();
                   1829:     unless (ref($idshashref) eq 'HASH') {
                   1830:         return %result;
                   1831:     }
                   1832:     my %servers=();
                   1833:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1834:         my $uhom;
                   1835:         if ($uhome) {
                   1836:             $uhom = $uhome;
                   1837:         } else {
                   1838:             $uhom=&homeserver($uname,$udom);
                   1839:         }
                   1840:         if ($uhom ne 'no_host') {
                   1841:             if ($servers{$uhom}) {
                   1842:                 $servers{$uhom}.='&'.&escape($id);
                   1843:             } else {
                   1844:                 $servers{$uhom}=&escape($id);
                   1845:             }
                   1846:         }
                   1847:     }
                   1848:     foreach my $server (keys(%servers)) {
                   1849:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1850:     }
                   1851:     return %result;
                   1852: }
                   1853: 
1.1023    raeburn  1854: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1855: sub dump_dom {
1.1165    droeschl 1856:     my ($namespace, $udom, $regexp) = @_;
                   1857: 
                   1858:     $udom ||= $env{'user.domain'};
                   1859: 
                   1860:     return () unless $udom;
                   1861: 
                   1862:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1863: }
                   1864: 
1.1023    raeburn  1865: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1866: 
                   1867: sub get_dom {
1.860     raeburn  1868:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1869:     return if ($udom eq 'public');
1.806     raeburn  1870:     my $items='';
                   1871:     foreach my $item (@$storearr) {
                   1872:         $items.=&escape($item).'&';
                   1873:     }
                   1874:     $items=~s/\&$//;
1.860     raeburn  1875:     if (!$udom) {
                   1876:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1877:         return if ($udom eq 'public');
1.860     raeburn  1878:         if (defined(&domain($udom,'primary'))) {
                   1879:             $uhome=&domain($udom,'primary');
                   1880:         } else {
1.874     albertel 1881:             undef($uhome);
1.860     raeburn  1882:         }
                   1883:     } else {
                   1884:         if (!$uhome) {
                   1885:             if (defined(&domain($udom,'primary'))) {
                   1886:                 $uhome=&domain($udom,'primary');
                   1887:             }
                   1888:         }
                   1889:     }
                   1890:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1891:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1892:         my %returnhash;
1.875     albertel 1893:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1894:             return %returnhash;
                   1895:         }
1.806     raeburn  1896:         my @pairs=split(/\&/,$rep);
                   1897:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1898:             return @pairs;
                   1899:         }
                   1900:         my $i=0;
                   1901:         foreach my $item (@$storearr) {
                   1902:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1903:             $i++;
                   1904:         }
                   1905:         return %returnhash;
                   1906:     } else {
1.880     banghart 1907:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1908:     }
                   1909: }
                   1910: 
                   1911: # -------------------------------------------- put items in domain db files 
                   1912: 
                   1913: sub put_dom {
1.860     raeburn  1914:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1915:     if (!$udom) {
                   1916:         $udom=$env{'user.domain'};
                   1917:         if (defined(&domain($udom,'primary'))) {
                   1918:             $uhome=&domain($udom,'primary');
                   1919:         } else {
1.874     albertel 1920:             undef($uhome);
1.860     raeburn  1921:         }
                   1922:     } else {
                   1923:         if (!$uhome) {
                   1924:             if (defined(&domain($udom,'primary'))) {
                   1925:                 $uhome=&domain($udom,'primary');
                   1926:             }
                   1927:         }
                   1928:     } 
                   1929:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1930:         my $items='';
                   1931:         foreach my $item (keys(%$storehash)) {
                   1932:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1933:         }
                   1934:         $items=~s/\&$//;
                   1935:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1936:     } else {
1.860     raeburn  1937:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1938:     }
                   1939: }
                   1940: 
1.1023    raeburn  1941: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1942: sub newput_dom {
1.1023    raeburn  1943:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1944:     my $result;
                   1945:     if (!$udom) {
                   1946:         $udom=$env{'user.domain'};
                   1947:     }
1.1023    raeburn  1948:     if ($udom) {
                   1949:         my $uname = &get_domainconfiguser($udom);
                   1950:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1951:     }
                   1952:     return $result;
                   1953: }
                   1954: 
1.1023    raeburn  1955: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1956: sub del_dom {
1.1023    raeburn  1957:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1958:     if (ref($storearr) eq 'ARRAY') {
                   1959:         if (!$udom) {
                   1960:             $udom=$env{'user.domain'};
                   1961:         }
1.1023    raeburn  1962:         if ($udom) {
                   1963:             my $uname = &get_domainconfiguser($udom); 
                   1964:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1965:         }
                   1966:     }
                   1967: }
                   1968: 
1.1023    raeburn  1969: # ----------------------------------construct domainconfig user for a domain 
                   1970: sub get_domainconfiguser {
                   1971:     my ($udom) = @_;
                   1972:     return $udom.'-domainconfig';
                   1973: }
                   1974: 
1.837     raeburn  1975: sub retrieve_inst_usertypes {
                   1976:     my ($udom) = @_;
                   1977:     my (%returnhash,@order);
1.989     raeburn  1978:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1979:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1980:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1981:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1982:     } else {
                   1983:         if (defined(&domain($udom,'primary'))) {
                   1984:             my $uhome=&domain($udom,'primary');
                   1985:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1986:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1987:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1988:                 return (\%returnhash,\@order);
                   1989:             }
                   1990:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1991:             my @pairs=split(/\&/,$hashitems);
                   1992:             foreach my $item (@pairs) {
                   1993:                 my ($key,$value)=split(/=/,$item,2);
                   1994:                 $key = &unescape($key);
                   1995:                 next if ($key =~ /^error: 2 /);
                   1996:                 $returnhash{$key}=&thaw_unescape($value);
                   1997:             }
                   1998:             my @esc_order = split(/\&/,$orderitems);
                   1999:             foreach my $item (@esc_order) {
                   2000:                 push(@order,&unescape($item));
                   2001:             }
                   2002:         } else {
1.1172.2.44  raeburn  2003:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2004:         }
1.1172.2.44  raeburn  2005:         return (\%returnhash,\@order);
1.837     raeburn  2006:     }
                   2007: }
                   2008: 
1.868     raeburn  2009: sub is_domainimage {
                   2010:     my ($url) = @_;
1.1172.2.74  raeburn  2011:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2012:         if (&domain($1) ne '') {
                   2013:             return '1';
                   2014:         }
                   2015:     }
                   2016:     return;
                   2017: }
                   2018: 
1.899     raeburn  2019: sub inst_directory_query {
                   2020:     my ($srch) = @_;
                   2021:     my $udom = $srch->{'srchdomain'};
                   2022:     my %results;
                   2023:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2024:     my $outcome;
1.899     raeburn  2025:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2026:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2027:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2028:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2029:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2030:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2031:                     (($major == 2) && ($minor < 11)) ||
                   2032:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2033:                     return;
                   2034:                 }
                   2035:             }
                   2036:         }
1.904     albertel 2037: 	my $queryid=&reply("querysend:instdirsearch:".
                   2038: 			   &escape($srch->{'srchby'}).':'.
                   2039: 			   &escape($srch->{'srchterm'}).':'.
                   2040: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2041: 	my $host=&hostname($homeserver);
                   2042: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2043: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2044: 	    return;
                   2045: 	}
                   2046: 	my $response = &get_query_reply($queryid);
                   2047: 	my $maxtries = 5;
                   2048: 	my $tries = 1;
                   2049: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2050: 	    $response = &get_query_reply($queryid);
                   2051: 	    $tries ++;
                   2052: 	}
                   2053: 
                   2054:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2055:             if ($response eq 'unavailable') {
                   2056:                 $outcome = $response;
                   2057:             } else {
                   2058:                 $outcome = 'ok';
                   2059:                 my @matches = split(/\n/,$response);
                   2060:                 foreach my $match (@matches) {
                   2061:                     my ($key,$value) = split(/=/,$match);
                   2062:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2063:                 }
1.899     raeburn  2064:             }
                   2065:         }
                   2066:     }
1.909     raeburn  2067:     return ($outcome,%results);
1.899     raeburn  2068: }
                   2069: 
                   2070: sub usersearch {
                   2071:     my ($srch) = @_;
                   2072:     my $dom = $srch->{'srchdomain'};
                   2073:     my %results;
                   2074:     my %libserv = &all_library();
                   2075:     my $query = 'usersearch';
                   2076:     foreach my $tryserver (keys(%libserv)) {
                   2077:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2078:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2079:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2080:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2081:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2082:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2083:                              (($major == 2) && ($minor < 11)) ||
                   2084:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2085:                 }
                   2086:             }
1.899     raeburn  2087:             my $host=&hostname($tryserver);
                   2088:             my $queryid=
1.911     raeburn  2089:                 &reply("querysend:".&escape($query).':'.
                   2090:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2091:                        &escape($srch->{'srchtype'}).':'.
                   2092:                        &escape($srch->{'srchterm'}),$tryserver);
                   2093:             if ($queryid !~/^\Q$host\E\_/) {
                   2094:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2095:                 next;
1.899     raeburn  2096:             }
                   2097:             my $reply = &get_query_reply($queryid);
                   2098:             my $maxtries = 1;
                   2099:             my $tries = 1;
                   2100:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2101:                 $reply = &get_query_reply($queryid);
                   2102:                 $tries ++;
                   2103:             }
                   2104:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2105:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2106:             } else {
1.911     raeburn  2107:                 my @matches;
                   2108:                 if ($reply =~ /\n/) {
                   2109:                     @matches = split(/\n/,$reply);
                   2110:                 } else {
                   2111:                     @matches = split(/\&/,$reply);
                   2112:                 }
1.899     raeburn  2113:                 foreach my $match (@matches) {
                   2114:                     my ($uname,$udom,%userhash);
1.911     raeburn  2115:                     foreach my $entry (split(/:/,$match)) {
                   2116:                         my ($key,$value) =
                   2117:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2118:                         $userhash{$key} = $value;
                   2119:                         if ($key eq 'username') {
                   2120:                             $uname = $value;
                   2121:                         } elsif ($key eq 'domain') {
                   2122:                             $udom = $value;
1.911     raeburn  2123:                         }
1.899     raeburn  2124:                     }
                   2125:                     $results{$uname.':'.$udom} = \%userhash;
                   2126:                 }
                   2127:             }
                   2128:         }
                   2129:     }
                   2130:     return %results;
                   2131: }
                   2132: 
1.912     raeburn  2133: sub get_instuser {
                   2134:     my ($udom,$uname,$id) = @_;
                   2135:     my $homeserver = &domain($udom,'primary');
                   2136:     my ($outcome,%results);
                   2137:     if ($homeserver ne '') {
                   2138:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2139:                            &escape($id).':'.&escape($udom),$homeserver);
                   2140:         my $host=&hostname($homeserver);
                   2141:         if ($queryid !~/^\Q$host\E\_/) {
                   2142:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2143:             return;
                   2144:         }
                   2145:         my $response = &get_query_reply($queryid);
                   2146:         my $maxtries = 5;
                   2147:         my $tries = 1;
                   2148:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2149:             $response = &get_query_reply($queryid);
                   2150:             $tries ++;
                   2151:         }
                   2152:         if (!&error($response) && $response ne 'refused') {
                   2153:             if ($response eq 'unavailable') {
                   2154:                 $outcome = $response;
                   2155:             } else {
                   2156:                 $outcome = 'ok';
                   2157:                 my @matches = split(/\n/,$response);
                   2158:                 foreach my $match (@matches) {
                   2159:                     my ($key,$value) = split(/=/,$match);
                   2160:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2161:                 }
                   2162:             }
                   2163:         }
                   2164:     }
                   2165:     my %userinfo;
                   2166:     if (ref($results{$uname}) eq 'HASH') {
                   2167:         %userinfo = %{$results{$uname}};
                   2168:     } 
                   2169:     return ($outcome,%userinfo);
                   2170: }
                   2171: 
1.1172.2.69  raeburn  2172: sub get_multiple_instusers {
                   2173:     my ($udom,$users,$caller) = @_;
                   2174:     my ($outcome,$results);
                   2175:     if (ref($users) eq 'HASH') {
                   2176:         my $count = keys(%{$users});
                   2177:         my $requested = &freeze_escape($users);
                   2178:         my $homeserver = &domain($udom,'primary');
                   2179:         if ($homeserver ne '') {
                   2180:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2181:             my $host=&hostname($homeserver);
                   2182:             if ($queryid !~/^\Q$host\E\_/) {
                   2183:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2184:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2185:                 return ($outcome,$results);
                   2186:             }
                   2187:             my $response = &get_query_reply($queryid);
                   2188:             my $maxtries = 5;
                   2189:             if ($count > 100) {
                   2190:                 $maxtries = 1+int($count/20);
                   2191:             }
                   2192:             my $tries = 1;
                   2193:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2194:                 $response = &get_query_reply($queryid);
                   2195:                 $tries ++;
                   2196:             }
                   2197:             if ($response eq '') {
                   2198:                 $results = {};
                   2199:                 foreach my $key (keys(%{$users})) {
                   2200:                     my ($uname,$id);
                   2201:                     if ($caller eq 'id') {
                   2202:                         $id = $key;
                   2203:                     } else {
                   2204:                         $uname = $key;
                   2205:                     }
                   2206:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2207:                     $outcome = $resp;
                   2208:                     if ($resp eq 'ok') {
                   2209:                         %{$results} = (%{$results}, %info);
                   2210:                     } else {
                   2211:                         last;
                   2212:                     }
                   2213:                 }
                   2214:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2215:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2216:                     $outcome = $response;
                   2217:                 } else {
                   2218:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2219:                     if ($outcome eq 'ok') {
                   2220:                         $results = &thaw_unescape($userdata);
                   2221:                     }
                   2222:                 }
                   2223:             }
                   2224:         }
                   2225:     }
                   2226:     return ($outcome,$results);
                   2227: }
                   2228: 
1.912     raeburn  2229: sub inst_rulecheck {
1.923     raeburn  2230:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2231:     my %returnhash;
                   2232:     if ($udom ne '') {
                   2233:         if (ref($rules) eq 'ARRAY') {
                   2234:             @{$rules} = map {&escape($_);} (@{$rules});
                   2235:             my $rulestr = join(':',@{$rules});
                   2236:             my $homeserver=&domain($udom,'primary');
                   2237:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2238:                 my $response;
                   2239:                 if ($item eq 'username') {                
                   2240:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2241:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2242:                                               $homeserver));
1.923     raeburn  2243:                 } elsif ($item eq 'id') {
                   2244:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2245:                                               ':'.&escape($id).':'.$rulestr,
                   2246:                                               $homeserver));
1.945     raeburn  2247:                 } elsif ($item eq 'selfcreate') {
                   2248:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2249:                                                &escape($udom).':'.&escape($uname).
                   2250:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2251:                 }
1.912     raeburn  2252:                 if ($response ne 'refused') {
                   2253:                     my @pairs=split(/\&/,$response);
                   2254:                     foreach my $item (@pairs) {
                   2255:                         my ($key,$value)=split(/=/,$item,2);
                   2256:                         $key = &unescape($key);
                   2257:                         next if ($key =~ /^error: 2 /);
                   2258:                         $returnhash{$key}=&thaw_unescape($value);
                   2259:                     }
                   2260:                 }
                   2261:             }
                   2262:         }
                   2263:     }
                   2264:     return %returnhash;
                   2265: }
                   2266: 
                   2267: sub inst_userrules {
1.923     raeburn  2268:     my ($udom,$check) = @_;
1.912     raeburn  2269:     my (%ruleshash,@ruleorder);
                   2270:     if ($udom ne '') {
                   2271:         my $homeserver=&domain($udom,'primary');
                   2272:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2273:             my $response;
                   2274:             if ($check eq 'id') {
                   2275:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2276:                                  $homeserver);
1.943     raeburn  2277:             } elsif ($check eq 'email') {
                   2278:                 $response=&reply('instemailrules:'.&escape($udom),
                   2279:                                  $homeserver);
1.923     raeburn  2280:             } else {
                   2281:                 $response=&reply('instuserrules:'.&escape($udom),
                   2282:                                  $homeserver);
                   2283:             }
1.912     raeburn  2284:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2285:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2286:                 ($response ne 'no_such_host')) {
                   2287:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2288:                 my @pairs=split(/\&/,$hashitems);
                   2289:                 foreach my $item (@pairs) {
                   2290:                     my ($key,$value)=split(/=/,$item,2);
                   2291:                     $key = &unescape($key);
                   2292:                     next if ($key =~ /^error: 2 /);
                   2293:                     $ruleshash{$key}=&thaw_unescape($value);
                   2294:                 }
                   2295:                 my @esc_order = split(/\&/,$orderitems);
                   2296:                 foreach my $item (@esc_order) {
                   2297:                     push(@ruleorder,&unescape($item));
                   2298:                 }
                   2299:             }
                   2300:         }
                   2301:     }
                   2302:     return (\%ruleshash,\@ruleorder);
                   2303: }
                   2304: 
1.976     raeburn  2305: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2306: 
                   2307: sub get_domain_defaults {
1.1172.2.35  raeburn  2308:     my ($domain,$ignore_cache) = @_;
                   2309:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2310:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2311:     unless ($ignore_cache) {
                   2312:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2313:         if (defined($cached)) {
                   2314:             if (ref($result) eq 'HASH') {
                   2315:                 return %{$result};
                   2316:             }
1.943     raeburn  2317:         }
                   2318:     }
                   2319:     my %domdefaults;
                   2320:     my %domconfig =
1.989     raeburn  2321:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2322:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2323:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2324:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2325:                                   'coursecategories','autoenroll',
                   2326:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2327:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2328:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2329:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2330:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2331:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2332:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2333:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2334:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2335:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2336:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2337:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2338:     } else {
                   2339:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2340:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2341:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2342:     }
1.976     raeburn  2343:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2344:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2345:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2346:         } else {
                   2347:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2348:         }
1.1172.2.6  raeburn  2349:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2350:         foreach my $item (@usertools) {
                   2351:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2352:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2353:             }
                   2354:         }
1.1172.2.29  raeburn  2355:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2356:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2357:         }
1.976     raeburn  2358:     }
1.985     raeburn  2359:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2360:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2361:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2362:         }
                   2363:     }
1.1172.2.9  raeburn  2364:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2365:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2366:     }
1.989     raeburn  2367:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2368:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2369:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2370:         }
                   2371:     }
1.1047    raeburn  2372:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2373:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2374:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2375:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2376:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2377:         }
1.1172.2.41  raeburn  2378:         foreach my $type (@coursetypes) {
                   2379:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2380:                 unless ($type eq 'community') {
                   2381:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2382:                 }
                   2383:             }
                   2384:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2385:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2386:             }
1.1172.2.60  raeburn  2387:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2388:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2389:                     $domdefaults{$type.'postsubtimeout'} =
                   2390:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2391:                 }
                   2392:             }
1.1172.2.30  raeburn  2393:         }
1.1172.2.67  raeburn  2394:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2395:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2396:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2397:                 if (@clonecodes) {
                   2398:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2399:                 }
                   2400:             }
                   2401:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2402:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2403:         }
1.1172.2.103  raeburn  2404:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2405:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2406:         }
1.1047    raeburn  2407:     }
1.1073    raeburn  2408:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2409:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2410:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2411:         }
                   2412:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2413:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2414:         }
1.1172.2.62  raeburn  2415:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2416:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2417:         }
1.1073    raeburn  2418:     }
1.1172.2.41  raeburn  2419:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2420:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2421:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2422:                             'approval','limit');
                   2423:             foreach my $type (@coursetypes) {
                   2424:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2425:                     my @mgrdc = ();
                   2426:                     foreach my $item (@settings) {
                   2427:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2428:                             push(@mgrdc,$item);
                   2429:                         }
                   2430:                     }
                   2431:                     if (@mgrdc) {
                   2432:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2433:                     }
                   2434:                 }
                   2435:             }
                   2436:         }
                   2437:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2438:             foreach my $type (@coursetypes) {
                   2439:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2440:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2441:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2442:                     }
                   2443:                 }
                   2444:             }
                   2445:         }
                   2446:     }
1.1172.2.46  raeburn  2447:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2448:         $domdefaults{'catauth'} = 'std';
                   2449:         $domdefaults{'catunauth'} = 'std';
                   2450:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2451:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2452:         }
                   2453:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2454:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2455:         }
                   2456:     }
1.1172.2.76  raeburn  2457:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2458:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2459:     }
1.1172.2.89  raeburn  2460:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2461:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2462:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2463:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2464:         }
                   2465:     }
1.1172.2.23  raeburn  2466:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2467:     return %domdefaults;
                   2468: }
                   2469: 
1.1172.2.106  raeburn  2470: sub get_dom_cats {
                   2471:     my ($dom) = @_;
                   2472:     return unless (&domain($dom));
                   2473:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2474:     unless (defined($cached)) {
                   2475:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2476:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2477:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2478:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2479:             } else {
                   2480:                 $cats = {};
                   2481:             }
                   2482:         } else {
                   2483:             $cats = {};
                   2484:         }
                   2485:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2486:     }
                   2487:     return $cats;
                   2488: }
                   2489: 
                   2490: sub get_dom_instcats {
                   2491:     my ($dom) = @_;
                   2492:     return unless (&domain($dom));
                   2493:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2494:     unless (defined($cached)) {
                   2495:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2496:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2497:         if ($totcodes > 0) {
                   2498:             my $caller = 'global';
                   2499:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2500:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2501:                 $instcats = {
                   2502:                                 codes => \%codes,
                   2503:                                 codetitles => \@codetitles,
                   2504:                                 cat_titles => \%cat_titles,
                   2505:                                 cat_order => \%cat_order,
                   2506:                             };
                   2507:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2508:             }
                   2509:         }
                   2510:     }
                   2511:     return $instcats;
                   2512: }
                   2513: 
                   2514: sub retrieve_instcodes {
                   2515:     my ($coursecodes,$dom) = @_;
                   2516:     my $totcodes;
                   2517:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2518:     foreach my $course (keys(%courses)) {
                   2519:         if (ref($courses{$course}) eq 'HASH') {
                   2520:             if ($courses{$course}{'inst_code'} ne '') {
                   2521:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2522:                 $totcodes ++;
                   2523:             }
                   2524:         }
                   2525:     }
                   2526:     return $totcodes;
                   2527: }
                   2528: 
1.1172.2.113  raeburn  2529: # --------------------------------------------- Get domain config for passwords
                   2530: 
                   2531: sub get_passwdconf {
                   2532:     my ($dom) = @_;
                   2533:     my (%passwdconf,$gotconf,$lookup);
                   2534:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2535:     if (defined($cached)) {
                   2536:         if (ref($result) eq 'HASH') {
                   2537:             %passwdconf = %{$result};
                   2538:             $gotconf = 1;
                   2539:         }
                   2540:     }
                   2541:     unless ($gotconf) {
                   2542:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2543:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2544:             %passwdconf = %{$domconfig{'passwords'}};
                   2545:         }
                   2546:         my $cachetime = 24*60*60;
                   2547:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2548:     }
                   2549:     return %passwdconf;
                   2550: }
                   2551: 
1.344     www      2552: # --------------------------------------------------- Assign a key to a student
                   2553: 
                   2554: sub assign_access_key {
1.364     www      2555: #
                   2556: # a valid key looks like uname:udom#comments
                   2557: # comments are being appended
                   2558: #
1.498     www      2559:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2560:     $kdom=
1.620     albertel 2561:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2562:     $knum=
1.620     albertel 2563:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2564:     $cdom=
1.620     albertel 2565:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2566:     $cnum=
1.620     albertel 2567:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2568:     $udom=$env{'user.name'} unless (defined($udom));
                   2569:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2570:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2571:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2572:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2573:                                                   # assigned to this person
                   2574:                                                   # - this should not happen,
1.345     www      2575:                                                   # unless something went wrong
                   2576:                                                   # the first time around
                   2577: # ready to assign
1.364     www      2578:         $logentry=$1.'; '.$logentry;
1.496     www      2579:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2580:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2581: # key now belongs to user
1.346     www      2582: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2583:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2584:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2585:                 return 'ok';
                   2586:             } else {
                   2587:                 return 
                   2588:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2589: 	    }
                   2590:         } else {
                   2591:             return 'error: Could not assign key, try again later.';
                   2592:         }
1.364     www      2593:     } elsif (!$existing{$ckey}) {
1.345     www      2594: # the key does not exist
                   2595: 	return 'error: The key does not exist';
                   2596:     } else {
                   2597: # the key is somebody else's
                   2598: 	return 'error: The key is already in use';
                   2599:     }
1.344     www      2600: }
                   2601: 
1.364     www      2602: # ------------------------------------------ put an additional comment on a key
                   2603: 
                   2604: sub comment_access_key {
                   2605: #
                   2606: # a valid key looks like uname:udom#comments
                   2607: # comments are being appended
                   2608: #
                   2609:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2610:     $cdom=
1.620     albertel 2611:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2612:     $cnum=
1.620     albertel 2613:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2614:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2615:     if ($existing{$ckey}) {
                   2616:         $existing{$ckey}.='; '.$logentry;
                   2617: # ready to assign
1.367     www      2618:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2619:                                                  $cdom,$cnum) eq 'ok') {
                   2620: 	    return 'ok';
                   2621:         } else {
                   2622: 	    return 'error: Count not store comment.';
                   2623:         }
                   2624:     } else {
                   2625: # the key does not exist
                   2626: 	return 'error: The key does not exist';
                   2627:     }
                   2628: }
                   2629: 
1.344     www      2630: # ------------------------------------------------------ Generate a set of keys
                   2631: 
                   2632: sub generate_access_keys {
1.364     www      2633:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2634:     $cdom=
1.620     albertel 2635:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2636:     $cnum=
1.620     albertel 2637:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2638:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2639:     unless (($cdom) && ($cnum)) { return 0; }
                   2640:     if ($number>10000) { return 0; }
                   2641:     sleep(2); # make sure don't get same seed twice
                   2642:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2643:     my $total=0;
                   2644:     for (my $i=1;$i<=$number;$i++) {
                   2645:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2646:                   sprintf("%lx",int(100000*rand)).'-'.
                   2647:                   sprintf("%lx",int(100000*rand));
                   2648:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2649:        $newkey=~s/0/h/g; # and also 0 and O
                   2650:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2651:        if ($existing{$newkey}) {
                   2652:            $i--;
                   2653:        } else {
1.364     www      2654: 	  if (&put('accesskeys',
                   2655:               { $newkey => '# generated '.localtime().
1.620     albertel 2656:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2657:                            '; '.$logentry },
                   2658: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2659:               $total++;
                   2660: 	  }
                   2661:        }
                   2662:     }
1.620     albertel 2663:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2664:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2665:     return $total;
                   2666: }
                   2667: 
                   2668: # ------------------------------------------------------- Validate an accesskey
                   2669: 
                   2670: sub validate_access_key {
                   2671:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2672:     $cdom=
1.620     albertel 2673:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2674:     $cnum=
1.620     albertel 2675:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2676:     $udom=$env{'user.domain'} unless (defined($udom));
                   2677:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2678:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2679:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2680: }
                   2681: 
                   2682: # ------------------------------------- Find the section of student in a course
1.652     albertel 2683: sub devalidate_getsection_cache {
                   2684:     my ($udom,$unam,$courseid)=@_;
                   2685:     my $hashid="$udom:$unam:$courseid";
                   2686:     &devalidate_cache_new('getsection',$hashid);
                   2687: }
1.298     matthew  2688: 
1.815     albertel 2689: sub courseid_to_courseurl {
                   2690:     my ($courseid) = @_;
                   2691:     #already url style courseid
                   2692:     return $courseid if ($courseid =~ m{^/});
                   2693: 
                   2694:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2695: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2696: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2697: 	return "/$cdom/$cnum";
                   2698:     }
                   2699: 
                   2700:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2701:     if (exists($courseinfo{'num'})) {
                   2702: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2703:     }
                   2704: 
                   2705:     return undef;
                   2706: }
                   2707: 
1.298     matthew  2708: sub getsection {
                   2709:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2710:     my $cachetime=1800;
1.551     albertel 2711: 
                   2712:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2713:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2714:     if (defined($cached)) { return $result; }
                   2715: 
1.298     matthew  2716:     my %Pending; 
                   2717:     my %Expired;
                   2718:     #
                   2719:     # Each role can either have not started yet (pending), be active, 
                   2720:     #    or have expired.
                   2721:     #
                   2722:     # If there is an active role, we are done.
                   2723:     #
                   2724:     # If there is more than one role which has not started yet, 
                   2725:     #     choose the one which will start sooner
                   2726:     # If there is one role which has not started yet, return it.
                   2727:     #
                   2728:     # If there is more than one expired role, choose the one which ended last.
                   2729:     # If there is a role which has expired, return it.
                   2730:     #
1.815     albertel 2731:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2732:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2733:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2734:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2735:         my $section=$1;
                   2736:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2737:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2738:         my $now=time;
1.548     albertel 2739:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2740:             $Expired{$end}=$section;
                   2741:             next;
                   2742:         }
1.548     albertel 2743:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2744:             $Pending{$start}=$section;
                   2745:             next;
                   2746:         }
1.599     albertel 2747:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2748:     }
                   2749:     #
                   2750:     # Presumedly there will be few matching roles from the above
                   2751:     # loop and the sorting time will be negligible.
                   2752:     if (scalar(keys(%Pending))) {
                   2753:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2754:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2755:     } 
                   2756:     if (scalar(keys(%Expired))) {
                   2757:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2758:         my $time = pop(@sorted);
1.599     albertel 2759:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2760:     }
1.599     albertel 2761:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2762: }
1.70      www      2763: 
1.599     albertel 2764: sub save_cache {
                   2765:     &purge_remembered();
1.722     albertel 2766:     #&Apache::loncommon::validate_page();
1.620     albertel 2767:     undef(%env);
1.780     albertel 2768:     undef($env_loaded);
1.599     albertel 2769: }
1.452     albertel 2770: 
1.599     albertel 2771: my $to_remember=-1;
                   2772: my %remembered;
                   2773: my %accessed;
                   2774: my $kicks=0;
                   2775: my $hits=0;
1.849     albertel 2776: sub make_key {
                   2777:     my ($name,$id) = @_;
1.872     albertel 2778:     if (length($id) > 65 
                   2779: 	&& length(&escape($id)) > 200) {
                   2780: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2781:     }
1.849     albertel 2782:     return &escape($name.':'.$id);
                   2783: }
                   2784: 
1.599     albertel 2785: sub devalidate_cache_new {
                   2786:     my ($name,$id,$debug) = @_;
                   2787:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2788:     my $remembered_id=$name.':'.$id;
1.849     albertel 2789:     $id=&make_key($name,$id);
1.599     albertel 2790:     $memcache->delete($id);
1.1172.2.81  raeburn  2791:     delete($remembered{$remembered_id});
                   2792:     delete($accessed{$remembered_id});
1.599     albertel 2793: }
                   2794: 
                   2795: sub is_cached_new {
                   2796:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2797:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2798:                                      # keys in %remembered hash, which persists for
                   2799:                                      # duration of request (no restriction on key length).
                   2800:     if (exists($remembered{$remembered_id})) {
                   2801: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2802: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2803: 	$hits++;
1.1172.2.81  raeburn  2804: 	return ($remembered{$remembered_id},1);
1.599     albertel 2805:     }
1.1172.2.81  raeburn  2806:     $id=&make_key($name,$id);
1.599     albertel 2807:     my $value = $memcache->get($id);
                   2808:     if (!(defined($value))) {
                   2809: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2810: 	return (undef,undef);
1.416     albertel 2811:     }
1.599     albertel 2812:     if ($value eq '__undef__') {
                   2813: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2814: 	$value=undef;
                   2815:     }
1.1172.2.81  raeburn  2816:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2817:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2818:     return ($value,1);
                   2819: }
                   2820: 
                   2821: sub do_cache_new {
                   2822:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2823:     my $remembered_id=$name.':'.$id;
1.849     albertel 2824:     $id=&make_key($name,$id);
1.599     albertel 2825:     my $setvalue=$value;
                   2826:     if (!defined($setvalue)) {
                   2827: 	$setvalue='__undef__';
                   2828:     }
1.623     albertel 2829:     if (!defined($time) ) {
                   2830: 	$time=600;
                   2831:     }
1.599     albertel 2832:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2833:     my $result = $memcache->set($id,$setvalue,$time);
                   2834:     if (! $result) {
1.872     albertel 2835: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2836: 	$memcache->disconnect_all();
1.872     albertel 2837:     }
1.600     albertel 2838:     # need to make a copy of $value
1.1172.2.81  raeburn  2839:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2840:     return $value;
                   2841: }
                   2842: 
                   2843: sub make_room {
1.1172.2.81  raeburn  2844:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2845: 
1.1172.2.81  raeburn  2846:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2847:                                     : $value;
1.599     albertel 2848:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2849:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2850:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2851:     my $to_kick;
                   2852:     my $max_time=0;
                   2853:     foreach my $other (keys(%accessed)) {
                   2854: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2855: 	    $to_kick=$other;
                   2856: 	    $max_time=&tv_interval($accessed{$other});
                   2857: 	}
                   2858:     }
                   2859:     delete($remembered{$to_kick});
                   2860:     delete($accessed{$to_kick});
                   2861:     $kicks++;
                   2862:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2863:     return;
                   2864: }
                   2865: 
1.599     albertel 2866: sub purge_remembered {
1.604     albertel 2867:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2868:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2869:     undef(%remembered);
                   2870:     undef(%accessed);
1.428     albertel 2871: }
1.70      www      2872: # ------------------------------------- Read an entry from a user's environment
                   2873: 
                   2874: sub userenvironment {
                   2875:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2876:     my $items;
                   2877:     foreach my $item (@what) {
                   2878:         $items.=&escape($item).'&';
                   2879:     }
                   2880:     $items=~s/\&$//;
1.70      www      2881:     my %returnhash=();
1.1009    raeburn  2882:     my $uhome = &homeserver($unam,$udom);
                   2883:     unless ($uhome eq 'no_host') {
                   2884:         my @answer=split(/\&/, 
                   2885:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2886:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2887:             return %returnhash;
                   2888:         }
1.1009    raeburn  2889:         my $i;
                   2890:         for ($i=0;$i<=$#what;$i++) {
                   2891: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2892:         }
1.70      www      2893:     }
                   2894:     return %returnhash;
1.1       albertel 2895: }
                   2896: 
1.617     albertel 2897: # ---------------------------------------------------------- Get a studentphoto
                   2898: sub studentphoto {
                   2899:     my ($udom,$unam,$ext) = @_;
                   2900:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2901:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2902:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2903:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2904:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2905:             } else {
                   2906:                 my ($result,$perm_reqd)=
1.707     albertel 2907: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2908:                 if ($result eq 'ok') {
                   2909:                     if (!($perm_reqd eq 'yes')) {
                   2910:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2911:                     }
                   2912:                 }
                   2913:             }
                   2914:         }
                   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:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2925: }
                   2926: 
                   2927: sub retrievestudentphoto {
                   2928:     my ($udom,$unam,$ext,$type) = @_;
                   2929:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2930:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2931:     if ($ret eq 'ok') {
                   2932:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2933:         if ($type eq 'thumbnail') {
                   2934:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2935:         }
                   2936:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2937:         return $tokenurl;
                   2938:     } else {
                   2939:         if ($type eq 'thumbnail') {
                   2940:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2941:         } else { 
                   2942:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2943:         }
1.617     albertel 2944:     }
                   2945: }
                   2946: 
1.263     www      2947: # -------------------------------------------------------------------- New chat
                   2948: 
                   2949: sub chatsend {
1.724     raeburn  2950:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2951:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2952:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2953:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2954:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2955: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2956: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2957: }
                   2958: 
                   2959: # ------------------------------------------ Find current version of a resource
                   2960: 
                   2961: sub getversion {
                   2962:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2963:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2964:     return &currentversion(&filelocation('',$fname));
                   2965: }
                   2966: 
                   2967: sub currentversion {
                   2968:     my $fname=shift;
                   2969:     my $author=$fname;
                   2970:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2971:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2972:     my $home=&homeserver($uname,$udom);
1.292     www      2973:     if ($home eq 'no_host') { 
                   2974:         return -1; 
                   2975:     }
1.1112    www      2976:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2977:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2978: 	return -1;
                   2979:     }
1.1112    www      2980:     return $answer;
1.263     www      2981: }
                   2982: 
1.1111    www      2983: #
                   2984: # Return special version number of resource if set by override, empty otherwise
                   2985: #
                   2986: sub usedversion {
                   2987:     my $fname=shift;
                   2988:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2989:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2990:     if ($urlversion) { return $urlversion; }
                   2991:     return '';
                   2992: }
                   2993: 
1.1       albertel 2994: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2995: 
1.1       albertel 2996: sub subscribe {
                   2997:     my $fname=shift;
1.761     raeburn  2998:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2999:     $fname=~s/[\n\r]//g;
1.1       albertel 3000:     my $author=$fname;
                   3001:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3002:     my ($udom,$uname)=split(/\//,$author);
                   3003:     my $home=homeserver($uname,$udom);
1.335     albertel 3004:     if ($home eq 'no_host') {
                   3005:         return 'not_found';
1.1       albertel 3006:     }
                   3007:     my $answer=reply("sub:$fname",$home);
1.64      www      3008:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3009: 	$answer.=' by '.$home;
                   3010:     }
1.1       albertel 3011:     return $answer;
                   3012: }
                   3013:     
1.8       www      3014: # -------------------------------------------------------------- Replicate file
                   3015: 
                   3016: sub repcopy {
                   3017:     my $filename=shift;
1.23      www      3018:     $filename=~s/\/+/\//g;
1.1142    raeburn  3019:     my $londocroot = $perlvar{'lonDocRoot'};
                   3020:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3021:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3022:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3023: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3024: 	return &repcopy_userfile($filename);
                   3025:     }
1.532     albertel 3026:     $filename=~s/[\n\r]//g;
1.8       www      3027:     my $transname="$filename.in.transfer";
1.828     www      3028: # FIXME: this should flock
1.607     raeburn  3029:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3030:     my $remoteurl=subscribe($filename);
1.64      www      3031:     if ($remoteurl =~ /^con_lost by/) {
                   3032: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3033:            return 'unavailable';
1.8       www      3034:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3035: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3036: 	   return 'not_found';
1.64      www      3037:     } elsif ($remoteurl =~ /^rejected by/) {
                   3038: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3039:            return 'forbidden';
1.20      www      3040:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3041:            return 'ok';
1.8       www      3042:     } else {
1.290     www      3043:         my $author=$filename;
                   3044:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3045:         my ($udom,$uname)=split(/\//,$author);
                   3046:         my $home=homeserver($uname,$udom);
                   3047:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3048:            my @parts=split(/\//,$filename);
                   3049:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3050:            if ($path ne "$londocroot/res") {
1.8       www      3051:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3052: 	       return 'bad_request';
1.8       www      3053:            }
                   3054:            my $count;
                   3055:            for ($count=5;$count<$#parts;$count++) {
                   3056:                $path.="/$parts[$count]";
                   3057:                if ((-e $path)!=1) {
                   3058: 		   mkdir($path,0777);
                   3059:                }
                   3060:            }
                   3061:            my $ua=new LWP::UserAgent;
                   3062:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3063:            my $response=$ua->request($request,$transname);
                   3064:            if ($response->is_error()) {
                   3065: 	       unlink($transname);
                   3066:                my $message=$response->status_line;
1.672     albertel 3067:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3068:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3069:                return 'unavailable';
1.8       www      3070:            } else {
1.16      www      3071: 	       if ($remoteurl!~/\.meta$/) {
                   3072:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3073:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3074:                   if ($mresponse->is_error()) {
                   3075: 		      unlink($filename.'.meta');
                   3076:                       &logthis(
1.672     albertel 3077:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3078:                   }
                   3079: 	       }
1.8       www      3080:                rename($transname,$filename);
1.607     raeburn  3081:                return 'ok';
1.8       www      3082:            }
1.290     www      3083:        }
1.8       www      3084:     }
1.330     www      3085: }
                   3086: 
1.1172.2.124  raeburn  3087: # ------------------------------------------------- Unsubscribe from a resource
                   3088: 
                   3089: sub unsubscribe {
                   3090:     my ($fname) = @_;
                   3091:     my $answer;
                   3092:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3093:     $fname=~s/[\n\r]//g;
                   3094:     my $author=$fname;
                   3095:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3096:     my ($udom,$uname)=split(/\//,$author);
                   3097:     my $home=homeserver($uname,$udom);
                   3098:     if ($home eq 'no_host') {
                   3099:         $answer = 'no_host';
                   3100:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3101:         $answer = 'home';
                   3102:     } else {
1.1172.2.125  raeburn  3103:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3104:     }
                   3105:     return $answer;
                   3106: }
                   3107: 
1.330     www      3108: # ------------------------------------------------ Get server side include body
                   3109: sub ssi_body {
1.381     albertel 3110:     my ($filelink,%form)=@_;
1.606     matthew  3111:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3112:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3113:     }
1.953     www      3114:     my $output='';
                   3115:     my $response;
1.980     raeburn  3116:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3117:        ($output,$response)=&externalssi($filelink);
1.953     www      3118:     } else {
1.1004    droeschl 3119:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3120:        $filelink .= 'inhibitmenu=yes';
1.953     www      3121:        ($output,$response)=&ssi($filelink,%form);
                   3122:     }
1.778     albertel 3123:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3124:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3125:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3126:     if (wantarray) {
                   3127:         return ($output, $response);
                   3128:     } else {
                   3129:         return $output;
                   3130:     }
1.8       www      3131: }
                   3132: 
1.15      www      3133: # --------------------------------------------------------- Server Side Include
                   3134: 
1.782     albertel 3135: sub absolute_url {
                   3136:     my ($host_name) = @_;
                   3137:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3138:     if ($host_name eq '') {
                   3139: 	$host_name = $ENV{'SERVER_NAME'};
                   3140:     }
                   3141:     return $protocol.$host_name;
                   3142: }
                   3143: 
1.942     foxr     3144: #
                   3145: #   Server side include.
                   3146: # Parameters:
                   3147: #  fn     Possibly encrypted resource name/id.
                   3148: #  form   Hash that describes how the rendering should be done
                   3149: #         and other things.
1.944     foxr     3150: # Returns:
1.950     raeburn  3151: #   Scalar context: The content of the response.
                   3152: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3153: #     
1.15      www      3154: sub ssi {
                   3155: 
1.944     foxr     3156:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3157:     my ($request,$response);
1.711     albertel 3158: 
                   3159:     $form{'no_update_last_known'}=1;
1.895     albertel 3160:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3161:     if (%form) {
1.782     albertel 3162:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3163:       $request->content(join('&',map {
                   3164:             my $name = escape($_);
                   3165:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3166:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3167:             : &escape($form{$_}) );
                   3168:         } keys(%form)));
1.23      www      3169:     } else {
1.782     albertel 3170:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3171:     }
                   3172: 
1.15      www      3173:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3174: 
1.1172.2.101  raeburn  3175:     if (($env{'request.course.id'}) &&
                   3176:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3177:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3178:         ($form{'grade_symb'} ne '') &&
                   3179:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3180:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3181:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3182:             my $ua=new LWP::UserAgent;
                   3183:             $ua->local_address('127.0.0.1');
                   3184:             $response = $ua->request($request);
                   3185:         } else {
                   3186:             {
                   3187:                 require LWP::Protocol::http;
                   3188:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3189:                 my $ua=new LWP::UserAgent;
                   3190:                 $response = $ua->request($request);
                   3191:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3192:             }
                   3193:         }
                   3194:     } else {
                   3195:         my $ua=new LWP::UserAgent;
                   3196:         $response = $ua->request($request);
                   3197:     }
1.944     foxr     3198:     if (wantarray) {
1.1172.2.3  raeburn  3199: 	return ($response->content, $response);
1.944     foxr     3200:     } else {
1.1172.2.3  raeburn  3201: 	return $response->content;
1.942     foxr     3202:     }
1.324     www      3203: }
                   3204: 
                   3205: sub externalssi {
                   3206:     my ($url)=@_;
                   3207:     my $ua=new LWP::UserAgent;
                   3208:     my $request=new HTTP::Request('GET',$url);
                   3209:     my $response=$ua->request($request);
1.954     raeburn  3210:     if (wantarray) {
                   3211:         return ($response->content, $response);
                   3212:     } else {
                   3213:         return $response->content;
                   3214:     }
1.15      www      3215: }
1.254     www      3216: 
1.1172.2.98  raeburn  3217: # If the local copy of a replicated resource is outdated, trigger a
                   3218: # connection from the homeserver to flush the delayed queue. If no update
                   3219: # happens, remove local copies of outdated resource (and corresponding
                   3220: # metadata file).
                   3221: 
                   3222: sub remove_stale_resfile {
                   3223:     my ($url) = @_;
                   3224:     my $removed;
                   3225:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3226:         my $audom = $1;
                   3227:         my $auname = $2;
                   3228:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3229:             my $homeserver = &homeserver($auname,$audom);
                   3230:             unless (($homeserver eq 'no_host') ||
                   3231:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3232:                 my $fname = &filelocation('',$url);
                   3233:                 if (-e $fname) {
                   3234:                     my $hostname = &hostname($homeserver);
                   3235:                     if ($hostname) {
1.1172.2.120  raeburn  3236:                         my $protocol = $protocol{$homeserver};
                   3237:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3238:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3239:                         my $ua=new LWP::UserAgent;
                   3240:                         $ua->timeout(5);
1.1172.2.98  raeburn  3241:                         my $request=new HTTP::Request('HEAD',$uri);
                   3242:                         my $response=$ua->request($request);
                   3243:                         if ($response->is_success()) {
                   3244:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3245:                             my $locmodtime = (stat($fname))[9];
                   3246:                             if ($locmodtime < $remmodtime) {
                   3247:                                 my $stale;
                   3248:                                 my $answer = &reply('pong',$homeserver);
                   3249:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3250:                                     sleep(0.2);
                   3251:                                     $locmodtime = (stat($fname))[9];
                   3252:                                     if ($locmodtime < $remmodtime) {
                   3253:                                         my $posstransfer = $fname.'.in.transfer';
                   3254:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3255:                                             $removed = 1;
                   3256:                                         } else {
                   3257:                                             $stale = 1;
                   3258:                                         }
                   3259:                                     } else {
                   3260:                                         $removed = 1;
                   3261:                                     }
                   3262:                                 } else {
                   3263:                                     $stale = 1;
                   3264:                                 }
                   3265:                                 if ($stale) {
1.1172.2.124  raeburn  3266:                                     if (unlink($fname)) {
                   3267:                                         if ($uri!~/\.meta$/) {
                   3268:                                             if (-e $fname.'.meta') {
                   3269:                                                 unlink($fname.'.meta');
                   3270:                                             }
                   3271:                                         }
                   3272:                                         my $unsubresult = &unsubscribe($fname);
                   3273:                                         unless ($unsubresult eq 'ok') {
                   3274:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3275:                                         }
                   3276:                                         $removed = 1;
1.1172.2.98  raeburn  3277:                                     }
                   3278:                                 }
                   3279:                             }
                   3280:                         }
                   3281:                     }
                   3282:                 }
                   3283:             }
                   3284:         }
                   3285:     }
                   3286:     return $removed;
                   3287: }
                   3288: 
1.492     albertel 3289: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3290: 
                   3291: sub allowuploaded {
                   3292:     my ($srcurl,$url)=@_;
                   3293:     $url=&clutter(&declutter($url));
                   3294:     my $dir=$url;
                   3295:     $dir=~s/\/[^\/]+$//;
                   3296:     my %httpref=();
                   3297:     my $httpurl=&hreflocation('',$url);
                   3298:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3299:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3300: }
1.477     raeburn  3301: 
1.1172.2.13  raeburn  3302: #
                   3303: # Determine if the current user should be able to edit a particular resource,
                   3304: # when viewing in course context.
                   3305: # (a) When viewing resource used to determine if "Edit" item is included in
                   3306: #     Functions.
                   3307: # (b) When displaying folder contents in course editor, used to determine if
                   3308: #     "Edit" link will be displayed alongside resource.
                   3309: #
                   3310: #  input: six args -- filename (decluttered), course number, course domain,
                   3311: #                   url, symb (if registered) and group (if this is a group
                   3312: #                   item -- e.g., bulletin board, group page etc.).
                   3313: #  output: array of five scalars --
                   3314: #          $cfile -- url for file editing if editable on current server
                   3315: #          $home -- homeserver of resource (i.e., for author if published,
                   3316: #                                           or course if uploaded.).
                   3317: #          $switchserver --  1 if server switch will be needed.
                   3318: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3319: #          $forceview -- 1 if icon/link should be to go to view mode
                   3320: #
                   3321: 
                   3322: sub can_edit_resource {
                   3323:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3324:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3325: #
                   3326: # For aboutme pages user can only edit his/her own.
                   3327: #
                   3328:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3329:         my ($sdom,$sname) = ($1,$2);
                   3330:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3331:             $home = $env{'user.home'};
                   3332:             $cfile = $resurl;
                   3333:             if ($env{'form.forceedit'}) {
                   3334:                 $forceview = 1;
                   3335:             } else {
                   3336:                 $forceedit = 1;
                   3337:             }
                   3338:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3339:         } else {
                   3340:             return;
                   3341:         }
                   3342:     }
                   3343: 
                   3344:     if ($env{'request.course.id'}) {
                   3345:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3346:         if ($group ne '') {
                   3347: # if this is a group homepage or group bulletin board, check group privs
                   3348:             my $allowed = 0;
                   3349:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3350:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3351:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3352:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3353:                     $allowed = 1;
                   3354:                 }
                   3355:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3356:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3357:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3358:                     $allowed = 1;
                   3359:                 }
                   3360:             }
                   3361:             if ($allowed) {
                   3362:                 $home=&homeserver($cnum,$cdom);
                   3363:                 if ($env{'form.forceedit'}) {
                   3364:                     $forceview = 1;
                   3365:                 } else {
                   3366:                     $forceedit = 1;
                   3367:                 }
                   3368:                 $cfile = $resurl;
                   3369:             } else {
                   3370:                 return;
                   3371:             }
                   3372:         } else {
1.1172.2.15  raeburn  3373:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3374:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3375:                     return;
                   3376:                 }
                   3377:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3378: #
                   3379: # No edit allowed where CC has switched to student role.
                   3380: #
                   3381:                 return;
                   3382:             }
                   3383:         }
                   3384:     }
                   3385: 
                   3386:     if ($file ne '') {
                   3387:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3388:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3389:                 $uploaded = 1;
                   3390:                 $incourse = 1;
                   3391:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3392:                     $cfile = &hreflocation('',$file);
                   3393:                     if ($env{'form.forceedit'}) {
                   3394:                         $forceview = 1;
                   3395:                     } else {
                   3396:                         $forceedit = 1;
                   3397:                     }
                   3398:                 }
                   3399:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3400:                 $incourse = 1;
                   3401:                 if ($env{'form.forceedit'}) {
                   3402:                     $forceview = 1;
                   3403:                 } else {
                   3404:                     $forceedit = 1;
                   3405:                 }
                   3406:                 $cfile = $resurl;
                   3407:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3408:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3409:                     $incourse = 1;
                   3410:                     if ($env{'form.forceedit'}) {
                   3411:                         $forceview = 1;
                   3412:                     } else {
                   3413:                         $forceedit = 1;
                   3414:                     }
                   3415:                     $cfile = $resurl;
                   3416:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3417:                     $incourse = 1;
                   3418:                     $cfile = $resurl.'/smpedit';
                   3419:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3420:                     $incourse = 1;
                   3421:                     if ($env{'form.forceedit'}) {
                   3422:                         $forceview = 1;
                   3423:                     } else {
                   3424:                         $forceedit = 1;
                   3425:                     }
                   3426:                     $cfile = $resurl;
1.1172.2.122  raeburn  3427:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3428:                     my ($map,$id,$res) = &decode_symb($symb);
                   3429:                     if ($map =~ /\.page$/) {
                   3430:                         $incourse = 1;
                   3431:                         if ($env{'form.forceedit'}) {
                   3432:                             $forceview = 1;
                   3433:                             $cfile = $map;
                   3434:                         } else {
                   3435:                             $forceedit = 1;
                   3436:                             $cfile =  '/adm/wrapper'.$resurl;
                   3437:                         }
                   3438:                     }
1.1172.2.15  raeburn  3439:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3440:                     $incourse = 1;
                   3441:                     if ($env{'form.forceedit'}) {
                   3442:                         $forceview = 1;
                   3443:                     } else {
                   3444:                         $forceedit = 1;
                   3445:                     }
                   3446:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3447:                 }
                   3448:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3449:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3450:                 if (&is_on_map($template)) {
                   3451:                     $incourse = 1;
                   3452:                     $forceview = 1;
                   3453:                     $cfile = $template;
                   3454:                 }
                   3455:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3456:                 $incourse = 1;
                   3457:                 if ($env{'form.forceedit'}) {
                   3458:                     $forceview = 1;
                   3459:                 } else {
                   3460:                     $forceedit = 1;
                   3461:                 }
                   3462:                 $cfile = $resurl;
1.1172.2.13  raeburn  3463:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3464:                 $incourse = 1;
                   3465:                 $forceview = 1;
                   3466:                 if ($symb) {
                   3467:                     my ($map,$id,$res)=&decode_symb($symb);
                   3468:                     $env{'request.symb'} = $symb;
                   3469:                     $cfile = &clutter($res);
                   3470:                 } else {
                   3471:                     $cfile = $env{'form.suppurl'};
                   3472:                     $cfile =~ s{^http://}{};
                   3473:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3474:                 }
1.1172.2.31  raeburn  3475:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3476:                 if ($env{'form.forceedit'}) {
                   3477:                     $forceview = 1;
                   3478:                 } else {
                   3479:                     $forceedit = 1;
                   3480:                 }
                   3481:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3482:             }
                   3483:         }
                   3484:         if ($uploaded || $incourse) {
                   3485:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3486:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3487:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3488:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3489:             # Check that the user has permission to edit this resource
                   3490:             my $setpriv = 1;
                   3491:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3492:             if (defined($cfudom)) {
                   3493:                 $home=&homeserver($cfuname,$cfudom);
                   3494:                 $cfile=$file;
                   3495:             }
                   3496:         }
                   3497:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3498:             (($home ne '') && ($home ne 'no_host'))) {
                   3499:             my @ids=&current_machine_ids();
                   3500:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3501:                 $switchserver=1;
                   3502:             }
                   3503:         }
                   3504:     }
                   3505:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3506: }
                   3507: 
                   3508: sub is_course_upload {
                   3509:     my ($file,$cnum,$cdom) = @_;
                   3510:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3511:     $uploadpath =~ s{^\/}{};
                   3512:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3513:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3514:         return 1;
                   3515:     }
                   3516:     return;
                   3517: }
                   3518: 
                   3519: sub in_course {
                   3520:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3521:     if ($hideprivileged) {
                   3522:         my $skipuser;
1.1172.2.23  raeburn  3523:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3524:         my @possdoms = ($cdom);
                   3525:         if ($coursehash{'checkforpriv'}) {
                   3526:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3527:         }
                   3528:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3529:             $skipuser = 1;
                   3530:             if ($coursehash{'nothideprivileged'}) {
                   3531:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3532:                     my $user;
                   3533:                     if ($item =~ /:/) {
                   3534:                         $user = $item;
                   3535:                     } else {
                   3536:                         $user = join(':',split(/[\@]/,$item));
                   3537:                     }
                   3538:                     if ($user eq $uname.':'.$udom) {
                   3539:                         undef($skipuser);
                   3540:                         last;
                   3541:                     }
                   3542:                 }
                   3543:             }
                   3544:             if ($skipuser) {
                   3545:                 return 0;
                   3546:             }
                   3547:         }
                   3548:     }
                   3549:     $type ||= 'any';
                   3550:     if (!defined($cdom) || !defined($cnum)) {
                   3551:         my $cid  = $env{'request.course.id'};
                   3552:         $cdom = $env{'course.'.$cid.'.domain'};
                   3553:         $cnum = $env{'course.'.$cid.'.num'};
                   3554:     }
                   3555:     my $typesref;
                   3556:     if (($type eq 'any') || ($type eq 'all')) {
                   3557:         $typesref = ['active','previous','future'];
                   3558:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3559:         $typesref = [$type];
                   3560:     }
                   3561:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3562:                               $typesref,undef,[$cdom]);
                   3563:     my ($tmp) = keys(%roles);
                   3564:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3565:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3566:     if (@course_roles > 0) {
                   3567:         return 1;
                   3568:     }
                   3569:     return 0;
                   3570: }
                   3571: 
1.478     albertel 3572: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3573: # input: action, courseID, current domain, intended
1.637     raeburn  3574: #        path to file, source of file, instruction to parse file for objects,
                   3575: #        ref to hash for embedded objects,
                   3576: #        ref to hash for codebase of java objects.
1.1095    raeburn  3577: #        reference to scalar to accommodate mime type determined
                   3578: #          from File::MMagic if $parser = parse.
1.637     raeburn  3579: #
1.485     raeburn  3580: # output: url to file (if action was uploaddoc), 
                   3581: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3582: #
1.478     albertel 3583: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3584: # course.
1.477     raeburn  3585: #
1.478     albertel 3586: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3587: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3588: #          course's home server.
1.477     raeburn  3589: #
1.478     albertel 3590: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3591: #          be copied from $source (current location) to 
                   3592: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3593: #         and will then be copied to
                   3594: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3595: #         course's home server.
1.485     raeburn  3596: #
1.481     raeburn  3597: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3598: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3599: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3600: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3601: #         in course's home server.
1.637     raeburn  3602: #
1.477     raeburn  3603: 
                   3604: sub process_coursefile {
1.1095    raeburn  3605:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3606:         $mimetype)=@_;
1.477     raeburn  3607:     my $fetchresult;
1.638     albertel 3608:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3609:     if ($action eq 'propagate') {
1.638     albertel 3610:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3611: 			     $home);
1.481     raeburn  3612:     } else {
1.477     raeburn  3613:         my $fpath = '';
                   3614:         my $fname = $file;
1.478     albertel 3615:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3616:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3617:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3618:         if ($action eq 'copy') {
                   3619:             if ($source eq '') {
                   3620:                 $fetchresult = 'no source file';
                   3621:                 return $fetchresult;
                   3622:             } else {
                   3623:                 my $destination = $filepath.'/'.$fname;
                   3624:                 rename($source,$destination);
                   3625:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3626:                                  $home);
1.481     raeburn  3627:             }
                   3628:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3629:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3630:             print $fh $env{'form.'.$source};
1.481     raeburn  3631:             close($fh);
1.637     raeburn  3632:             if ($parser eq 'parse') {
1.1024    raeburn  3633:                 my $mm = new File::MMagic;
1.1095    raeburn  3634:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3635:                 if ($type eq 'text/html') {
1.1024    raeburn  3636:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3637:                     unless ($parse_result eq 'ok') {
                   3638:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3639:                     }
1.637     raeburn  3640:                 }
1.1095    raeburn  3641:                 if (ref($mimetype)) {
                   3642:                     $$mimetype = $type;
                   3643:                 } 
1.637     raeburn  3644:             }
1.477     raeburn  3645:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3646:                                  $home);
1.481     raeburn  3647:             if ($fetchresult eq 'ok') {
                   3648:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3649:             } else {
                   3650:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3651:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3652:                 return '/adm/notfound.html';
                   3653:             }
1.477     raeburn  3654:         }
                   3655:     }
1.485     raeburn  3656:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3657:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3658:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3659:     }
                   3660:     return $fetchresult;
                   3661: }
                   3662: 
1.637     raeburn  3663: sub build_filepath {
                   3664:     my ($fpath) = @_;
                   3665:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3666:     unless ($fpath eq '') {
                   3667:         my @parts=split('/',$fpath);
                   3668:         foreach my $part (@parts) {
                   3669:             $filepath.= '/'.$part;
                   3670:             if ((-e $filepath)!=1) {
                   3671:                 mkdir($filepath,0777);
                   3672:             }
                   3673:         }
                   3674:     }
                   3675:     return $filepath;
                   3676: }
                   3677: 
                   3678: sub store_edited_file {
1.638     albertel 3679:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3680:     my $file = $primary_url;
                   3681:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3682:     my $fpath = '';
                   3683:     my $fname = $file;
                   3684:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3685:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3686:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3687:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3688:     print $fh $content;
                   3689:     close($fh);
1.638     albertel 3690:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3691:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3692: 			  $home);
1.637     raeburn  3693:     if ($$fetchresult eq 'ok') {
                   3694:         return '/uploaded/'.$fpath.'/'.$fname;
                   3695:     } else {
1.638     albertel 3696:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3697: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3698:         return '/adm/notfound.html';
                   3699:     }
                   3700: }
                   3701: 
1.531     albertel 3702: sub clean_filename {
1.831     albertel 3703:     my ($fname,$args)=@_;
1.315     www      3704: # Replace Windows backslashes by forward slashes
1.257     www      3705:     $fname=~s/\\/\//g;
1.831     albertel 3706:     if (!$args->{'keep_path'}) {
                   3707:         # Get rid of everything but the actual filename
                   3708: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3709:     }
1.315     www      3710: # Replace spaces by underscores
                   3711:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3712: # Transliterate non-ascii text to ascii
                   3713:     my $lang = &Apache::lonlocal::current_language();
                   3714:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3715: # Replace all other weird characters by nothing
1.831     albertel 3716:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3717: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3718: # numbers
                   3719:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3720:     return $fname;
                   3721: }
1.1172.2.110  raeburn  3722: 
1.1051    raeburn  3723: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3724: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3725: # image with the same aspect ratio as the original, but with dimensions which do 
                   3726: # not exceed $resizewidth and $resizeheight.
                   3727:  
1.984     neumanie 3728: sub resizeImage {
1.1051    raeburn  3729:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3730:     my $ima = Image::Magick->new;
                   3731:     my $resized;
                   3732:     if (-e $img_path) {
                   3733:         $ima->Read($img_path);
                   3734:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3735:             my $width = $ima->Get('width');
                   3736:             my $height = $ima->Get('height');
                   3737:             if ($width > $resizewidth) {
                   3738: 	        my $factor = $width/$resizewidth;
                   3739:                 my $newheight = $height/$factor;
                   3740:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3741:                 $resized = 1;
                   3742:             }
                   3743:         }
                   3744:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3745:             my $width = $ima->Get('width');
                   3746:             my $height = $ima->Get('height');
                   3747:             if ($height > $resizeheight) {
                   3748:                 my $factor = $height/$resizeheight;
                   3749:                 my $newwidth = $width/$factor;
                   3750:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3751:                 $resized = 1;
                   3752:             }
                   3753:         }
                   3754:         if ($resized) {
                   3755:             $ima->Write($img_path);
                   3756:         }
                   3757:     }
                   3758:     return;
1.977     amueller 3759: }
                   3760: 
1.608     albertel 3761: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3762: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3763: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3764: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3765: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3766: #                   if 'coursedoc': upload to the current course
                   3767: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3768: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3769: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3770: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3771: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3772: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3773: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3774: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3775: #        $allfiles - reference to hash for embedded objects
                   3776: #        $codebase - reference to hash for codebase of java objects
                   3777: #        $desuname - username for permanent storage of uploaded file
                   3778: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3779: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3780: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3781: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3782: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3783: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3784: #                    from File::MMagic.
1.858     raeburn  3785: # 
1.686     albertel 3786: # output: url of file in userspace, or error: <message> 
                   3787: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3788: 
1.531     albertel 3789: sub userfileupload {
1.1090    raeburn  3790:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3791:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3792:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3793:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3794:     $fname=&clean_filename($fname);
1.1090    raeburn  3795:     # See if there is anything left
1.257     www      3796:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3797:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3798:     if ($fname =~ /^\./) {
                   3799:         my ($s,$usec) = &gettimeofday();
                   3800:         while (length($usec) < 6) {
                   3801:             $usec = '0'.$usec;
                   3802:         }
                   3803:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3804:     }
1.1090    raeburn  3805:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3806:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3807:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3808:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3809:         my $now = time;
1.1090    raeburn  3810:         my $filepath;
1.1095    raeburn  3811:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3812:              $filepath = 'tmp/helprequests/'.$now;
                   3813:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3814:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3815:                          '_'.$env{'user.domain'}.'/pending';
                   3816:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3817:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3818:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3819:                 $docudom = $destudom;
                   3820:             } else {
                   3821:                 $docudom = $env{'user.domain'};
                   3822:             }
1.1172.2.96  raeburn  3823:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3824:                 $docuname = $destuname;
                   3825:             } else {
                   3826:                 $docuname = $env{'user.name'};
                   3827:             }
                   3828:             if (exists($env{'form.group'})) {
                   3829:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3830:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3831:             }
                   3832:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3833:             if ($context eq 'canceloverwrite') {
                   3834:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3835:                 if (-e  $tempfile) {
                   3836:                     my @info = stat($tempfile);
                   3837:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3838:                         unlink($tempfile);
                   3839:                     }
                   3840:                 }
                   3841:                 return;
1.523     raeburn  3842:             }
                   3843:         }
1.1090    raeburn  3844:         # Create the directory if not present
1.741     raeburn  3845:         my @parts=split(/\//,$filepath);
                   3846:         my $fullpath = $perlvar{'lonDaemons'};
                   3847:         for (my $i=0;$i<@parts;$i++) {
                   3848:             $fullpath .= '/'.$parts[$i];
                   3849:             if ((-e $fullpath)!=1) {
                   3850:                 mkdir($fullpath,0777);
                   3851:             }
                   3852:         }
1.1172.2.96  raeburn  3853:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3854:         print $fh $env{'form.'.$formname};
                   3855:         close($fh);
1.1090    raeburn  3856:         if ($context eq 'existingfile') {
                   3857:             my @info = stat($fullpath.'/'.$fname);
                   3858:             return ($fullpath.'/'.$fname,$info[9]);
                   3859:         } else {
                   3860:             return $fullpath.'/'.$fname;
                   3861:         }
1.523     raeburn  3862:     }
1.995     raeburn  3863:     if ($subdir eq 'scantron') {
                   3864:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3865:     } else {
1.995     raeburn  3866:         $fname="$subdir/$fname";
                   3867:     }
1.1090    raeburn  3868:     if ($context eq 'coursedoc') {
1.638     albertel 3869: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3870: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3871:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3872:             return &finishuserfileupload($docuname,$docudom,
                   3873: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3874: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3875:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3876:         } else {
1.1172.2.21  raeburn  3877:             if ($env{'form.folder'}) {
                   3878:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3879:             }
1.638     albertel 3880:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3881: 				       $fname,$formname,$parser,
1.1095    raeburn  3882: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3883:         }
1.719     banghart 3884:     } elsif (defined($destuname)) {
                   3885:         my $docuname=$destuname;
                   3886:         my $docudom=$destudom;
1.860     raeburn  3887: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3888: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3889:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3890:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3891:     } else {
1.638     albertel 3892:         my $docuname=$env{'user.name'};
                   3893:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3894:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3895:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3896:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3897:         }
1.860     raeburn  3898: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3899: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3900:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3901:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3902:     }
1.271     www      3903: }
                   3904: 
                   3905: sub finishuserfileupload {
1.860     raeburn  3906:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3907:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3908:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3909:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3910:   
1.860     raeburn  3911:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3912:     $file=$fname;
                   3913:     if ($fname=~m|/|) {
                   3914:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3915: 	$path.=$fnamepath.'/';
                   3916:     }
1.259     www      3917:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3918:     my $count;
                   3919:     for ($count=4;$count<=$#parts;$count++) {
                   3920:         $filepath.="/$parts[$count]";
                   3921:         if ((-e $filepath)!=1) {
                   3922: 	    mkdir($filepath,0777);
                   3923:         }
                   3924:     }
1.984     neumanie 3925: 
1.258     www      3926: # Save the file
                   3927:     {
1.1172.2.96  raeburn  3928: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3929: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3930: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3931: 	    return '/adm/notfound.html';
                   3932: 	}
1.1090    raeburn  3933:         if ($context eq 'overwrite') {
1.1117    foxr     3934:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3935:             my $target = $filepath.'/'.$file;
                   3936:             if (-e $source) {
                   3937:                 my @info = stat($source);
                   3938:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3939:                     unless (&File::Copy::move($source,$target)) {
                   3940:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3941:                         return "Moving from $source failed";
                   3942:                     }
                   3943:                 } else {
                   3944:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3945:                 }
                   3946:             } else {
                   3947:                 return "Temporary file: $source missing";
                   3948:             }
                   3949:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3950: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3951: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3952: 	    return '/adm/notfound.html';
                   3953: 	}
1.570     albertel 3954: 	close(FH);
1.1051    raeburn  3955:         if ($resizewidth && $resizeheight) {
                   3956:             my $mm = new File::MMagic;
                   3957:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3958:             if ($mime_type =~ m{^image/}) {
                   3959: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3960:             }  
1.977     amueller 3961: 	}
1.258     www      3962:     }
1.1152    raeburn  3963:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3964:         if (ref($mimetype)) {
                   3965:             if ($$mimetype eq '') {
                   3966:                 my $mm = new File::MMagic;
                   3967:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3968:                 $$mimetype = $type;
                   3969:             }
                   3970:         }
                   3971:     }
1.1172.2.109  raeburn  3972:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3973:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3974:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3975:                                                        $allfiles,$codebase);
                   3976:             unless ($parse_result eq 'ok') {
                   3977:                 &logthis('Failed to parse '.$filepath.$file.
                   3978: 	   	         ' for embedded media: '.$parse_result); 
                   3979:             }
1.637     raeburn  3980:         }
1.1172.2.109  raeburn  3981:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3982:         my $format = $env{'form.scantron_format'};
                   3983:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3984:     }
1.860     raeburn  3985:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3986:         my $input = $filepath.'/'.$file;
                   3987:         my $output = $filepath.'/'.'tn-'.$file;
                   3988:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3989:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3990:         system({$args[0]} @args);
1.860     raeburn  3991:         if (-e $filepath.'/'.'tn-'.$file) {
                   3992:             $fetchthumb  = 1; 
                   3993:         }
                   3994:     }
1.858     raeburn  3995:  
1.259     www      3996: # Notify homeserver to grep it
                   3997: #
1.984     neumanie 3998:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3999:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4000:     if ($fetchresult eq 'ok') {
1.860     raeburn  4001:         if ($fetchthumb) {
                   4002:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4003:             if ($thumbresult ne 'ok') {
                   4004:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4005:                          $docuhome.': '.$thumbresult);
                   4006:             }
                   4007:         }
1.259     www      4008: #
1.258     www      4009: # Return the URL to it
1.494     albertel 4010:         return '/uploaded/'.$path.$file;
1.263     www      4011:     } else {
1.494     albertel 4012:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4013: 		 ': '.$fetchresult);
1.263     www      4014:         return '/adm/notfound.html';
1.858     raeburn  4015:     }
1.493     albertel 4016: }
                   4017: 
1.637     raeburn  4018: sub extract_embedded_items {
1.961     raeburn  4019:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4020:     my @state = ();
1.1164    raeburn  4021:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4022:     my %javafiles = (
                   4023:                       codebase => '',
                   4024:                       code => '',
                   4025:                       archive => ''
                   4026:                     );
                   4027:     my %mediafiles = (
                   4028:                       src => '',
                   4029:                       movie => '',
                   4030:                      );
1.648     raeburn  4031:     my $p;
                   4032:     if ($content) {
                   4033:         $p = HTML::LCParser->new($content);
                   4034:     } else {
1.961     raeburn  4035:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4036:     }
1.641     albertel 4037:     while (my $t=$p->get_token()) {
1.640     albertel 4038: 	if ($t->[0] eq 'S') {
                   4039: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4040: 	    push(@state, $tagname);
1.648     raeburn  4041:             if (lc($tagname) eq 'allow') {
                   4042:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4043:             }
1.640     albertel 4044: 	    if (lc($tagname) eq 'img') {
                   4045: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4046: 	    }
1.886     albertel 4047: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4048:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4049: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4050:                 }
1.886     albertel 4051: 	    }
1.645     raeburn  4052:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4053:                 my $src;
1.645     raeburn  4054:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4055:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4056:                 } else {
1.1164    raeburn  4057:                     if ($attr->{'src'} ne '') {
                   4058:                         $src = $attr->{'src'};
                   4059:                         &add_filetype($allfiles,$src,'src');
                   4060:                     }
                   4061:                 }
                   4062:                 my $text = $p->get_trimmed_text();
                   4063:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4064:                     my @swfargs = split(/,/,$1);
                   4065:                     foreach my $item (@swfargs) {
                   4066:                         $item =~ s/["']//g;
                   4067:                         $item =~ s/^\s+//;
                   4068:                         $item =~ s/\s+$//;
                   4069:                     }
                   4070:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4071:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4072:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4073:                         } else {
                   4074:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4075:                         }
                   4076:                     }
1.645     raeburn  4077:                 }
                   4078:             }
                   4079:             if (lc($tagname) eq 'link') {
                   4080:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4081:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4082:                 }
                   4083:             }
1.640     albertel 4084: 	    if (lc($tagname) eq 'object' ||
                   4085: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4086: 		foreach my $item (keys(%javafiles)) {
                   4087: 		    $javafiles{$item} = '';
                   4088: 		}
1.1164    raeburn  4089:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4090:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4091:                 }
1.640     albertel 4092: 	    }
                   4093: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4094: 		my $name = lc($attr->{'name'});
                   4095: 		foreach my $item (keys(%javafiles)) {
                   4096: 		    if ($name eq $item) {
                   4097: 			$javafiles{$item} = $attr->{'value'};
                   4098: 			last;
                   4099: 		    }
                   4100: 		}
1.1164    raeburn  4101:                 my $pathfrom;
1.640     albertel 4102: 		foreach my $item (keys(%mediafiles)) {
                   4103: 		    if ($name eq $item) {
1.1164    raeburn  4104:                         $pathfrom = $attr->{'value'};
                   4105:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4106: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4107: 			last;
                   4108: 		    }
                   4109: 		}
1.1164    raeburn  4110:                 if ($name eq 'flashvars') {
                   4111:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4112:                 }
                   4113:                 if ($pathfrom ne '') {
                   4114:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4115:                                          $pathfrom);
                   4116:                 }
1.640     albertel 4117: 	    }
                   4118: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4119: 		foreach my $item (keys(%javafiles)) {
                   4120: 		    if ($attr->{$item}) {
                   4121: 			$javafiles{$item} = $attr->{$item};
                   4122: 			last;
                   4123: 		    }
                   4124: 		}
                   4125: 		foreach my $item (keys(%mediafiles)) {
                   4126: 		    if ($attr->{$item}) {
                   4127: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4128: 			last;
                   4129: 		    }
                   4130: 		}
1.1164    raeburn  4131:                 if (lc($tagname) eq 'embed') {
                   4132:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4133:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4134:                                              $attr->{'src'});
                   4135:                     }
                   4136:                 }
1.640     albertel 4137: 	    }
1.1172.2.35  raeburn  4138:             if (lc($tagname) eq 'iframe') {
                   4139:                 my $src = $attr->{'src'} ;
                   4140:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4141:                     &add_filetype($allfiles,$src,'src');
                   4142:                 } elsif ($src =~ m{^/}) {
                   4143:                     if ($env{'request.course.id'}) {
                   4144:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4145:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4146:                         my $url = &hreflocation('',$fullpath);
                   4147:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4148:                             my $relpath = $1;
                   4149:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4150:                                 &add_filetype($allfiles,$1,'src');
                   4151:                             }
                   4152:                         }
                   4153:                     }
                   4154:                 }
                   4155:             }
1.1164    raeburn  4156:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4157:                 pop(@state);
1.1164    raeburn  4158:             }
1.640     albertel 4159: 	} elsif ($t->[0] eq 'E') {
                   4160: 	    my ($tagname) = ($t->[1]);
                   4161: 	    if ($javafiles{'codebase'} ne '') {
                   4162: 		$javafiles{'codebase'} .= '/';
                   4163: 	    }  
                   4164: 	    if (lc($tagname) eq 'applet' ||
                   4165: 		lc($tagname) eq 'object' ||
                   4166: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4167: 		) {
                   4168: 		foreach my $item (keys(%javafiles)) {
                   4169: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4170: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4171: 			&add_filetype($allfiles,$file,$item);
                   4172: 		    }
                   4173: 		}
                   4174: 	    } 
                   4175: 	    pop @state;
                   4176: 	}
                   4177:     }
1.1164    raeburn  4178:     foreach my $id (sort(keys(%flashvars))) {
                   4179:         if ($shockwave{$id} ne '') {
                   4180:             my @pairs = split(/\&/,$flashvars{$id});
                   4181:             foreach my $pair (@pairs) {
                   4182:                 my ($key,$value) = split(/\=/,$pair);
                   4183:                 if ($key eq 'thumb') {
                   4184:                     &add_filetype($allfiles,$value,$key);
                   4185:                 } elsif ($key eq 'content') {
                   4186:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4187:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4188:                     if ($ext ne '') {
                   4189:                         &add_filetype($allfiles,$path.$value,$ext);
                   4190:                     }
                   4191:                 }
                   4192:             }
                   4193:         }
                   4194:     }
1.637     raeburn  4195:     return 'ok';
                   4196: }
                   4197: 
1.639     albertel 4198: sub add_filetype {
                   4199:     my ($allfiles,$file,$type)=@_;
                   4200:     if (exists($allfiles->{$file})) {
                   4201: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4202: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4203: 	}
                   4204:     } else {
                   4205: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4206:     }
                   4207: }
                   4208: 
1.1164    raeburn  4209: sub embedded_dependency {
                   4210:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4211:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4212:         if (($identifier ne '') &&
                   4213:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4214:             ($pathfrom ne '')) {
                   4215:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4216:             foreach my $dep (@{$related->{$identifier}}) {
                   4217:                 &add_filetype($allfiles,$path.$dep,'object');
                   4218:             }
                   4219:         }
                   4220:     }
                   4221:     return;
                   4222: }
                   4223: 
1.1172.2.109  raeburn  4224: sub bubblesheet_converter {
                   4225:     my ($cdom,$fullpath,$config,$format) = @_;
                   4226:     if ((&domain($cdom) ne '') &&
                   4227:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4228:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4229:         my (%csvcols,%csvoptions);
                   4230:         if (ref($config->{'fields'}) eq 'HASH') {
                   4231:             %csvcols = %{$config->{'fields'}};
                   4232:         }
                   4233:         if (ref($config->{'options'}) eq 'HASH') {
                   4234:             %csvoptions = %{$config->{'options'}};
                   4235:         }
                   4236:         my %csvbynum = reverse(%csvcols);
                   4237:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4238:         if (keys(%scantronconf)) {
                   4239:             my %bynum = (
                   4240:                           $scantronconf{CODEstart} => 'CODEstart',
                   4241:                           $scantronconf{IDstart}   => 'IDstart',
                   4242:                           $scantronconf{PaperID}   => 'PaperID',
                   4243:                           $scantronconf{FirstName} => 'FirstName',
                   4244:                           $scantronconf{LastName}  => 'LastName',
                   4245:                           $scantronconf{Qstart}    => 'Qstart',
                   4246:                         );
                   4247:             my @ordered;
                   4248:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4249:                 push(@ordered,$bynum{$item});
                   4250:             }
                   4251:             my %mapstart = (
                   4252:                               CODEstart => 'CODE',
                   4253:                               IDstart   => 'ID',
                   4254:                               PaperID   => 'PaperID',
                   4255:                               FirstName => 'FirstName',
                   4256:                               LastName  => 'LastName',
                   4257:                               Qstart    => 'FirstQuestion',
                   4258:                            );
                   4259:             my %maplength = (
                   4260:                               CODEstart => 'CODElength',
                   4261:                               IDstart   => 'IDlength',
                   4262:                               PaperID   => 'PaperIDlength',
                   4263:                               FirstName => 'FirstNamelength',
                   4264:                               LastName  => 'LastNamelength',
                   4265:             );
                   4266:             if (open(my $fh,'<',$fullpath)) {
                   4267:                 my $output;
                   4268:                 my %lettdig = &letter_to_digits();
                   4269:                 my %diglett = reverse(%lettdig);
                   4270:                 my $numletts = scalar(keys(%lettdig));
                   4271:                 my $num = 0;
                   4272:                 while (my $line=<$fh>) {
                   4273:                     $num ++;
                   4274:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4275:                     $line =~ s{[\r\n]+$}{};
                   4276:                     my %found;
                   4277:                     my @values = split(/,/,$line);
                   4278:                     my ($qstart,$record);
                   4279:                     for (my $i=0; $i<@values; $i++) {
                   4280:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4281:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4282:                             if ($values[$i] eq '') {
                   4283:                                 $values[$i] = $scantronconf{'Qoff'};
                   4284:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4285:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4286:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4287:                                 }
                   4288:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4289:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4290:                                     $values[$i] = $diglett{$values[$i]};
                   4291:                                 }
                   4292:                             } else {
                   4293:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4294:                                     my $digit;
                   4295:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4296:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4297:                                         if ($values[$i] eq 'J') {
                   4298:                                             $digit += $numletts;
                   4299:                                         }
                   4300:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4301:                                         $digit = $values[$i]-1;
                   4302:                                         if ($values[$i] eq '0') {
                   4303:                                             $digit += $numletts;
                   4304:                                         }
                   4305:                                     }
                   4306:                                     my $qval='';
                   4307:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4308:                                         if ($j == $digit) {
                   4309:                                             $qval .= $scantronconf{'Qon'};
                   4310:                                         } else {
                   4311:                                             $qval .= $scantronconf{'Qoff'};
                   4312:                                         }
                   4313:                                     }
                   4314:                                     $values[$i] = $qval;
                   4315:                                 }
                   4316:                             }
                   4317:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4318:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4319:                             }
                   4320:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4321:                             if ($numblank > 0) {
                   4322:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4323:                             }
                   4324:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4325:                                 $qstart = $i;
                   4326:                                 $found{$csvbynum{$i}} = $values[$i];
                   4327:                             } else {
                   4328:                                 $found{'FirstQuestion'} .= $values[$i];
                   4329:                             }
                   4330:                         } elsif (exists($csvbynum{$i})) {
                   4331:                             if ($csvoptions{'rem'}) {
                   4332:                                 $values[$i] =~ s/^\s+//;
                   4333:                             }
                   4334:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4335:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4336:                                     $values[$i] = '0'.$values[$i];
                   4337:                                 }
                   4338:                             }
                   4339:                             $found{$csvbynum{$i}} = $values[$i];
                   4340:                         }
                   4341:                     }
                   4342:                     foreach my $item (@ordered) {
                   4343:                         my $currlength = 1+length($record);
                   4344:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4345:                         if ($numspaces > 0) {
                   4346:                             $record .= (' ' x $numspaces);
                   4347:                         }
                   4348:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4349:                             unless ($item eq 'Qstart') {
                   4350:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4351:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4352:                                 }
                   4353:                             }
                   4354:                             $record .= $found{$mapstart{$item}};
                   4355:                         }
                   4356:                     }
                   4357:                     $output .= "$record\n";
                   4358:                 }
                   4359:                 close($fh);
                   4360:                 if ($output) {
                   4361:                     if (open(my $fh,'>',$fullpath)) {
                   4362:                         print $fh $output;
                   4363:                         close($fh);
                   4364:                     }
                   4365:                 }
                   4366:             }
                   4367:         }
                   4368:         return;
                   4369:     }
                   4370: }
                   4371: 
                   4372: sub letter_to_digits {
                   4373:     my %lettdig = (
                   4374:                     A => 1,
                   4375:                     B => 2,
                   4376:                     C => 3,
                   4377:                     D => 4,
                   4378:                     E => 5,
                   4379:                     F => 6,
                   4380:                     G => 7,
                   4381:                     H => 8,
                   4382:                     I => 9,
                   4383:                     J => 0,
                   4384:                   );
                   4385:     return %lettdig;
                   4386: }
                   4387: 
                   4388: sub get_scantron_config {
                   4389:     my ($which,$cdom) = @_;
                   4390:     my @lines = &get_scantronformat_file($cdom);
                   4391:     my %config;
                   4392:     #FIXME probably should move to XML it has already gotten a bit much now
                   4393:     foreach my $line (@lines) {
                   4394:         my ($name,$descrip)=split(/:/,$line);
                   4395:         if ($name ne $which ) { next; }
                   4396:         chomp($line);
                   4397:         my @config=split(/:/,$line);
                   4398:         $config{'name'}=$config[0];
                   4399:         $config{'description'}=$config[1];
                   4400:         $config{'CODElocation'}=$config[2];
                   4401:         $config{'CODEstart'}=$config[3];
                   4402:         $config{'CODElength'}=$config[4];
                   4403:         $config{'IDstart'}=$config[5];
                   4404:         $config{'IDlength'}=$config[6];
                   4405:         $config{'Qstart'}=$config[7];
                   4406:         $config{'Qlength'}=$config[8];
                   4407:         $config{'Qoff'}=$config[9];
                   4408:         $config{'Qon'}=$config[10];
                   4409:         $config{'PaperID'}=$config[11];
                   4410:         $config{'PaperIDlength'}=$config[12];
                   4411:         $config{'FirstName'}=$config[13];
                   4412:         $config{'FirstNamelength'}=$config[14];
                   4413:         $config{'LastName'}=$config[15];
                   4414:         $config{'LastNamelength'}=$config[16];
                   4415:         $config{'BubblesPerRow'}=$config[17];
                   4416:         last;
                   4417:     }
                   4418:     return %config;
                   4419: }
                   4420: 
                   4421: sub get_scantronformat_file {
                   4422:     my ($cdom) = @_;
                   4423:     if ($cdom eq '') {
                   4424:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4425:     }
                   4426:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4427:     my $gottab = 0;
                   4428:     my @lines;
                   4429:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4430:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4431:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4432:             if ($formatfile ne '-1') {
                   4433:                 @lines = split("\n",$formatfile,-1);
                   4434:                 $gottab = 1;
                   4435:             }
                   4436:         }
                   4437:     }
                   4438:     if (!$gottab) {
                   4439:         my $confname = $cdom.'-domainconfig';
                   4440:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4441:         my $formatfile = &getfile($default);
                   4442:         if ($formatfile ne '-1') {
                   4443:             @lines = split("\n",$formatfile,-1);
                   4444:             $gottab = 1;
                   4445:         }
                   4446:     }
                   4447:     if (!$gottab) {
                   4448:         my @domains = &current_machine_domains();
                   4449:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4450:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4451:                 @lines = <$fh>;
                   4452:                 close($fh);
                   4453:             }
                   4454:         } else {
                   4455:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4456:                 @lines = <$fh>;
                   4457:                 close($fh);
                   4458:             }
                   4459:         }
                   4460:     }
                   4461:     return @lines;
                   4462: }
                   4463: 
1.493     albertel 4464: sub removeuploadedurl {
1.984     neumanie 4465:     my ($url)=@_;	
                   4466:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4467:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4468: }
                   4469: 
                   4470: sub removeuserfile {
                   4471:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4472:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4473:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4474:     if ($result eq 'ok') {	
1.798     raeburn  4475:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4476:             my $metafile = $fname.'.meta';
                   4477:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4478: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4479:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4480:             my $sqlresult = 
1.823     albertel 4481:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4482:                                         'portfolio_metadata',$group,
                   4483:                                         'delete');
1.798     raeburn  4484:         }
                   4485:     }
                   4486:     return $result;
1.257     www      4487: }
1.15      www      4488: 
1.530     albertel 4489: sub mkdiruserfile {
                   4490:     my ($docuname,$docudom,$dir)=@_;
                   4491:     my $home=&homeserver($docuname,$docudom);
                   4492:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4493: }
                   4494: 
1.531     albertel 4495: sub renameuserfile {
                   4496:     my ($docuname,$docudom,$old,$new)=@_;
                   4497:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4498:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4499:                         &escape("$old").':'.&escape("$new"),$home);
                   4500:     if ($result eq 'ok') {
                   4501:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4502:             my $oldmeta = $old.'.meta';
                   4503:             my $newmeta = $new.'.meta';
                   4504:             my $metaresult = 
                   4505:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4506: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4507:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4508:             my $sqlresult = 
1.823     albertel 4509:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4510:                                         'portfolio_metadata',$group,
                   4511:                                         'delete');
1.798     raeburn  4512:         }
                   4513:     }
                   4514:     return $result;
1.531     albertel 4515: }
                   4516: 
1.14      www      4517: # ------------------------------------------------------------------------- Log
                   4518: 
                   4519: sub log {
                   4520:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4521:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4522: }
                   4523: 
                   4524: # ------------------------------------------------------------------ Course Log
1.352     www      4525: #
                   4526: # This routine flushes several buffers of non-mission-critical nature
                   4527: #
1.157     www      4528: 
                   4529: sub flushcourselogs {
1.352     www      4530:     &logthis('Flushing log buffers');
                   4531: #
                   4532: # course logs
                   4533: # This is a log of all transactions in a course, which can be used
                   4534: # for data mining purposes
                   4535: #
                   4536: # It also collects the courseid database, which lists last transaction
                   4537: # times and course titles for all courseids
                   4538: #
                   4539:     my %courseidbuffer=();
1.921     raeburn  4540:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4541:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4542: 		          &escape($courselogs{$crsid}),
                   4543: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4544: 	    delete $courselogs{$crsid};
                   4545:         } else {
                   4546:             &logthis('Failed to flush log buffer for '.$crsid);
                   4547:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4548:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4549:                         " exceeded maximum size, deleting.</font>");
                   4550:                delete $courselogs{$crsid};
                   4551:             }
1.352     www      4552:         }
1.920     raeburn  4553:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4554:             'description' => $coursedescrbuf{$crsid},
                   4555:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4556:             'type'        => $coursetypebuf{$crsid},
                   4557:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4558:         };
1.191     harris41 4559:     }
1.352     www      4560: #
                   4561: # Write course id database (reverse lookup) to homeserver of courses 
                   4562: # Is used in pickcourse
                   4563: #
1.840     albertel 4564:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4565:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4566:                                     $courseidbuffer{$crs_home},
                   4567:                                     $crs_home,'timeonly');
1.352     www      4568:     }
                   4569: #
                   4570: # File accesses
                   4571: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4572: #
1.449     matthew  4573:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4574:         if ($entry =~ /___count$/) {
                   4575:             my ($dom,$name);
1.807     albertel 4576:             ($dom,$name,undef)=
1.811     albertel 4577: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4578:             if (! defined($dom) || $dom eq '' || 
                   4579:                 ! defined($name) || $name eq '') {
1.620     albertel 4580:                 my $cid = $env{'request.course.id'};
                   4581:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4582:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4583:             }
1.450     matthew  4584:             my $value = $accesshash{$entry};
                   4585:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4586:             my %temphash=($url => $value);
1.449     matthew  4587:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4588:             if ($result eq 'ok') {
                   4589:                 delete $accesshash{$entry};
                   4590:             }
                   4591:         } else {
1.811     albertel 4592:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4593:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4594:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4595:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4596:                 delete $accesshash{$entry};
                   4597:             }
1.185     www      4598:         }
1.191     harris41 4599:     }
1.352     www      4600: #
                   4601: # Roles
                   4602: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4603: #
1.800     albertel 4604:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4605:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4606: 	    split(/\:/,$entry);
                   4607:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4608:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4609:                 $rudom,$runame) eq 'ok') {
                   4610: 	    delete $userrolehash{$entry};
                   4611:         }
                   4612:     }
1.662     raeburn  4613: #
1.1172.2.90  raeburn  4614: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4615: #
                   4616:     my %domrolebuffer = ();
1.1000    raeburn  4617:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4618:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4619:         if ($domrolebuffer{$rudom}) {
                   4620:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4621:                       '='.&escape($domainrolehash{$entry});
                   4622:         } else {
                   4623:             $domrolebuffer{$rudom}.=&escape($entry).
                   4624:                       '='.&escape($domainrolehash{$entry});
                   4625:         }
                   4626:         delete $domainrolehash{$entry};
                   4627:     }
                   4628:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4629:         my %servers;
                   4630:         if (defined(&domain($dom,'primary'))) {
                   4631:             my $primary=&domain($dom,'primary');
                   4632:             my $hostname=&hostname($primary);
                   4633:             $servers{$primary} = $hostname;
                   4634:         } else {
                   4635:             %servers = &get_servers($dom,'library');
                   4636:         }
1.841     albertel 4637: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4638: 	    if (&reply('domroleput:'.$dom.':'.
                   4639: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4640: 	        last;
                   4641: 	    } else {
1.841     albertel 4642: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4643: 	    }
1.662     raeburn  4644:         }
                   4645:     }
1.186     www      4646:     $dumpcount++;
1.157     www      4647: }
                   4648: 
                   4649: sub courselog {
                   4650:     my $what=shift;
1.158     www      4651:     $what=time.':'.$what;
1.620     albertel 4652:     unless ($env{'request.course.id'}) { return ''; }
                   4653:     $coursedombuf{$env{'request.course.id'}}=
                   4654:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4655:     $coursenumbuf{$env{'request.course.id'}}=
                   4656:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4657:     $coursehombuf{$env{'request.course.id'}}=
                   4658:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4659:     $coursedescrbuf{$env{'request.course.id'}}=
                   4660:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4661:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4662:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4663:     $courseownerbuf{$env{'request.course.id'}}=
                   4664:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4665:     $coursetypebuf{$env{'request.course.id'}}=
                   4666:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4667:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4668: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4669:     } else {
1.620     albertel 4670: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4671:     }
1.620     albertel 4672:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4673: 	&flushcourselogs();
                   4674:     }
1.158     www      4675: }
                   4676: 
                   4677: sub courseacclog {
                   4678:     my $fnsymb=shift;
1.620     albertel 4679:     unless ($env{'request.course.id'}) { return ''; }
                   4680:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4681:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4682:         $what.=':POST';
1.583     matthew  4683:         # FIXME: Probably ought to escape things....
1.800     albertel 4684: 	foreach my $key (keys(%env)) {
                   4685:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4686:                 my $formitem = $1;
                   4687:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4688:                     $what.=':'.$formitem.'='.$env{$key};
                   4689:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4690:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132! raeburn  4691:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4692:                     } else {
                   4693:                         $what.=':'.$formitem.'='.$env{$key};
                   4694:                     }
1.975     raeburn  4695:                 }
1.158     www      4696:             }
1.191     harris41 4697:         }
1.583     matthew  4698:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4699:         # FIXME: We should not be depending on a form parameter that someone
                   4700:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4701:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4702:             $what.= ':POST';
                   4703:             # FIXME: Probably ought to escape things....
                   4704:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4705:                                  'crsdiscuss') {
1.620     albertel 4706:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4707:             }
                   4708:         }
1.158     www      4709:     }
                   4710:     &courselog($what);
1.149     www      4711: }
                   4712: 
1.185     www      4713: sub countacc {
                   4714:     my $url=&declutter(shift);
1.458     matthew  4715:     return if (! defined($url) || $url eq '');
1.620     albertel 4716:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4717: #
                   4718: # Mark that this url was used in this course
                   4719: #
1.620     albertel 4720:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4721: #
                   4722: # Increase the access count for this resource in this child process
                   4723: #
1.281     www      4724:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4725:     $accesshash{$key}++;
1.185     www      4726: }
1.349     www      4727: 
1.361     www      4728: sub linklog {
                   4729:     my ($from,$to)=@_;
                   4730:     $from=&declutter($from);
                   4731:     $to=&declutter($to);
                   4732:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4733:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4734: }
1.1160    www      4735: 
                   4736: sub statslog {
                   4737:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4738:     if ($users<2) { return; }
                   4739:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4740:             'course'       => $env{'request.course.id'},
                   4741:             'sections'     => '"all"',
                   4742:             'num_students' => $users,
                   4743:             'part'         => $part,
                   4744:             'symb'         => $symb,
                   4745:             'mean_tries'   => $av_attempts,
                   4746:             'deg_of_diff'  => $degdiff});
                   4747:     foreach my $key (keys(%dynstore)) {
                   4748:         $accesshash{$key}=$dynstore{$key};
                   4749:     }
                   4750: }
1.361     www      4751:   
1.349     www      4752: sub userrolelog {
                   4753:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4754:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4755:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4756:        $userrolehash
                   4757:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4758:                     =$tend.':'.$tstart;
1.662     raeburn  4759:     }
1.1169    droeschl 4760:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4761:        $userrolehash
                   4762:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4763:                     =$tend.':'.$tstart;
                   4764:     }
1.1172.2.90  raeburn  4765:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4766:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4767:        $domainrolehash
                   4768:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4769:                     = $tend.':'.$tstart;
                   4770:     }
1.351     www      4771: }
                   4772: 
1.957     raeburn  4773: sub courserolelog {
                   4774:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4775:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4776:         my $cdom = $1;
                   4777:         my $cnum = $2;
                   4778:         my $sec = $3;
                   4779:         my $namespace = 'rolelog';
                   4780:         my %storehash = (
                   4781:                            role    => $trole,
                   4782:                            start   => $tstart,
                   4783:                            end     => $tend,
                   4784:                            selfenroll => $selfenroll,
                   4785:                            context    => $context,
                   4786:                         );
                   4787:         if ($trole eq 'gr') {
                   4788:             $namespace = 'groupslog';
                   4789:             $storehash{'group'} = $sec;
                   4790:         } else {
                   4791:             $storehash{'section'} = $sec;
                   4792:         }
                   4793:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4794:                    $domain,$cnum,$cdom);
                   4795:         if (($trole ne 'st') || ($sec ne '')) {
                   4796:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4797:         }
                   4798:     }
                   4799:     return;
                   4800: }
                   4801: 
1.1172.2.9  raeburn  4802: sub domainrolelog {
                   4803:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4804:     if ($area =~ m{^/($match_domain)/$}) {
                   4805:         my $cdom = $1;
                   4806:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4807:         my $namespace = 'rolelog';
                   4808:         my %storehash = (
                   4809:                            role    => $trole,
                   4810:                            start   => $tstart,
                   4811:                            end     => $tend,
                   4812:                            context => $context,
                   4813:                         );
                   4814:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4815:                    $domain,$domconfiguser,$cdom);
                   4816:     }
                   4817:     return;
                   4818: 
                   4819: }
                   4820: 
                   4821: sub coauthorrolelog {
                   4822:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4823:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4824:         my $audom = $1;
                   4825:         my $auname = $2;
                   4826:         my $namespace = 'rolelog';
                   4827:         my %storehash = (
                   4828:                            role    => $trole,
                   4829:                            start   => $tstart,
                   4830:                            end     => $tend,
                   4831:                            context => $context,
                   4832:                         );
                   4833:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4834:                    $domain,$auname,$audom);
                   4835:     }
                   4836:     return;
                   4837: }
                   4838: 
1.351     www      4839: sub get_course_adv_roles {
1.948     raeburn  4840:     my ($cid,$codes) = @_;
1.620     albertel 4841:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4842:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4843:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4844:     my %nothide=();
1.800     albertel 4845:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4846:         if ($user !~ /:/) {
                   4847: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4848:         } else {
                   4849:             $nothide{$user}=1;
                   4850:         }
1.470     www      4851:     }
1.1172.2.23  raeburn  4852:     my @possdoms = ($coursehash{'domain'});
                   4853:     if ($coursehash{'checkforpriv'}) {
                   4854:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4855:     }
1.351     www      4856:     my %returnhash=();
                   4857:     my %dumphash=
                   4858:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4859:     my $now=time;
1.997     raeburn  4860:     my %privileged;
1.1000    raeburn  4861:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4862: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4863:         if (($tstart) && ($tstart<0)) { next; }
                   4864:         if (($tend) && ($tend<$now)) { next; }
                   4865:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4866:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4867: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4868:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4869:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4870: 	if ($role eq 'cr') { next; }
1.948     raeburn  4871:         if ($codes) {
                   4872:             if ($section) { $role .= ':'.$section; }
                   4873:             if ($returnhash{$role}) {
                   4874:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4875:             } else {
                   4876:                 $returnhash{$role}=$username.':'.$domain;
                   4877:             }
1.351     www      4878:         } else {
1.988     raeburn  4879:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4880:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4881:             if ($returnhash{$key}) {
                   4882: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4883:             } else {
                   4884:                 $returnhash{$key}=$username.':'.$domain;
                   4885:             }
1.351     www      4886:         }
1.948     raeburn  4887:     }
1.400     www      4888:     return %returnhash;
                   4889: }
                   4890: 
                   4891: sub get_my_roles {
1.937     raeburn  4892:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4893:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4894:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4895:     my (%dumphash,%nothide);
1.1086    raeburn  4896:     if ($context eq 'userroles') {
1.1166    raeburn  4897:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4898:     } else {
1.1172.2.23  raeburn  4899:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4900:         if ($hidepriv) {
                   4901:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4902:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4903:                 if ($user !~ /:/) {
                   4904:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4905:                 } else {
                   4906:                     $nothide{$user} = 1;
                   4907:                 }
                   4908:             }
                   4909:         }
1.858     raeburn  4910:     }
1.400     www      4911:     my %returnhash=();
                   4912:     my $now=time;
1.999     raeburn  4913:     my %privileged;
1.800     albertel 4914:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4915:         my ($role,$tend,$tstart);
                   4916:         if ($context eq 'userroles') {
1.1149    raeburn  4917:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4918: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4919:         } else {
                   4920:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4921:         }
1.400     www      4922:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4923:         my $status = 'active';
1.939     raeburn  4924:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4925:             $status = 'previous';
                   4926:         } 
                   4927:         if (($tstart) && ($now<$tstart)) {
                   4928:             $status = 'future';
                   4929:         }
                   4930:         if (ref($types) eq 'ARRAY') {
                   4931:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4932:                 next;
                   4933:             } 
                   4934:         } else {
                   4935:             if ($status ne 'active') {
                   4936:                 next;
                   4937:             }
                   4938:         }
1.867     raeburn  4939:         my ($rolecode,$username,$domain,$section,$area);
                   4940:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4941:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4942:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4943:         } else {
                   4944:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4945:         }
1.832     raeburn  4946:         if (ref($roledoms) eq 'ARRAY') {
                   4947:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4948:                 next;
                   4949:             }
                   4950:         }
                   4951:         if (ref($roles) eq 'ARRAY') {
                   4952:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4953:                 if ($role =~ /^cr\//) {
                   4954:                     if (!grep(/^cr$/,@{$roles})) {
                   4955:                         next;
                   4956:                     }
1.1104    raeburn  4957:                 } elsif ($role =~ /^gr\//) {
                   4958:                     if (!grep(/^gr$/,@{$roles})) {
                   4959:                         next;
                   4960:                     }
1.922     raeburn  4961:                 } else {
                   4962:                     next;
                   4963:                 }
1.832     raeburn  4964:             }
1.867     raeburn  4965:         }
1.937     raeburn  4966:         if ($hidepriv) {
1.1172.2.23  raeburn  4967:             my @privroles = ('dc','su');
1.999     raeburn  4968:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4969:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4970:             } else {
1.1172.2.23  raeburn  4971:                 my $possdoms = [$domain];
                   4972:                 if (ref($roledoms) eq 'ARRAY') {
                   4973:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4974:                 }
1.1172.2.23  raeburn  4975:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4976:                     if (!$nothide{$username.':'.$domain}) {
                   4977:                         next;
                   4978:                     }
                   4979:                 }
1.937     raeburn  4980:             }
                   4981:         }
1.933     raeburn  4982:         if ($withsec) {
                   4983:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4984:                 $tstart.':'.$tend;
                   4985:         } else {
                   4986:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4987:         }
1.832     raeburn  4988:     }
1.373     www      4989:     return %returnhash;
1.399     www      4990: }
                   4991: 
1.1172.2.89  raeburn  4992: sub get_all_adhocroles {
                   4993:     my ($dom) = @_;
                   4994:     my @roles_by_num = ();
                   4995:     my %domdefaults = &get_domain_defaults($dom);
                   4996:     my (%description,%access_in_dom,%access_info);
                   4997:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4998:         my $count = 0;
                   4999:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5000:         my %ordered;
                   5001:         foreach my $role (sort(keys(%domcurrent))) {
                   5002:             my ($order,$desc,$access_in_dom);
                   5003:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5004:                 $order = $domcurrent{$role}{'order'};
                   5005:                 $desc = $domcurrent{$role}{'desc'};
                   5006:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5007:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5008:             }
                   5009:             if ($order eq '') {
                   5010:                 $order = $count;
                   5011:             }
                   5012:             $ordered{$order} = $role;
                   5013:             if ($desc ne '') {
                   5014:                 $description{$role} = $desc;
                   5015:             } else {
                   5016:                 $description{$role}= $role;
                   5017:             }
                   5018:             $count++;
                   5019:         }
                   5020:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5021:             push(@roles_by_num,$ordered{$item});
                   5022:         }
                   5023:     }
                   5024:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5025: }
                   5026: 
                   5027: sub get_my_adhocroles {
                   5028:     my ($cid,$checkreg) = @_;
                   5029:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5030:     if ($env{'request.course.id'} eq $cid) {
                   5031:         $cdom = $env{'course.'.$cid.'.domain'};
                   5032:         $cnum = $env{'course.'.$cid.'.num'};
                   5033:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5034:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5035:         $cdom = $1;
                   5036:         $cnum = $2;
                   5037:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5038:                                      $cdom,$cnum);
                   5039:     }
                   5040:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5041:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5042:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5043:         if ($rosterhash{$user} ne '') {
                   5044:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5045:             return ([],{}) if ($type eq 'auto');
                   5046:         }
                   5047:     }
                   5048:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5049:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5050:             my $then=$env{'user.login.time'};
                   5051:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5052:             if (!$update) {
                   5053:                 $update = $then;
                   5054:             }
                   5055:             my @liveroles;
                   5056:             foreach my $role ('dh','da') {
                   5057:                 if ($env{"user.role.$role./$cdom/"}) {
                   5058:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5059:                     my $limit = $update;
                   5060:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5061:                         $limit = $then;
                   5062:                     }
                   5063:                     my $activerole = 1;
                   5064:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5065:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5066:                     if ($activerole) {
                   5067:                         push(@liveroles,$role);
                   5068:                     }
                   5069:                 }
                   5070:             }
                   5071:             if (@liveroles) {
1.1172.2.89  raeburn  5072:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5073:                     my ($accessref,$accessinfo,%access_in_dom);
                   5074:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5075:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5076:                         if (@{$roles_by_num}) {
                   5077:                             my %settings;
                   5078:                             if ($env{'request.course.id'} eq $cid) {
                   5079:                                 foreach my $envkey (keys(%env)) {
                   5080:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5081:                                         $settings{$1} = $env{$envkey};
                   5082:                                     }
                   5083:                                 }
                   5084:                             } else {
                   5085:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5086:                             }
                   5087:                             my %setincrs;
                   5088:                             if ($settings{'internal.adhocaccess'}) {
                   5089:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5090:                             }
                   5091:                             my @statuses;
                   5092:                             if ($env{'environment.inststatus'}) {
                   5093:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5094:                             }
                   5095:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5096:                             if (ref($accessref) eq 'HASH') {
                   5097:                                 %access_in_dom = %{$accessref};
                   5098:                             }
                   5099:                             foreach my $role (@{$roles_by_num}) {
                   5100:                                 my ($curraccess,@okstatus,@personnel);
                   5101:                                 if ($setincrs{$role}) {
                   5102:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5103:                                     if ($curraccess eq 'status') {
                   5104:                                         @okstatus = split(/\&/,$rest);
                   5105:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5106:                                         @personnel = split(/\&/,$rest);
                   5107:                                     }
                   5108:                                 } else {
                   5109:                                     $curraccess = $access_in_dom{$role};
                   5110:                                     if (ref($accessinfo) eq 'HASH') {
                   5111:                                         if ($curraccess eq 'status') {
                   5112:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5113:                                                 @okstatus = @{$accessinfo->{$role}};
                   5114:                                             }
                   5115:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5116:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5117:                                                 @personnel = @{$accessinfo->{$role}};
                   5118:                                             }
                   5119:                                         }
                   5120:                                     }
                   5121:                                 }
                   5122:                                 if ($curraccess eq 'none') {
                   5123:                                     next;
                   5124:                                 } elsif ($curraccess eq 'all') {
                   5125:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5126:                                 } elsif ($curraccess eq 'dh') {
                   5127:                                     if (grep(/^dh$/,@liveroles)) {
                   5128:                                         push(@possroles,$role);
                   5129:                                     } else {
                   5130:                                         next;
                   5131:                                     }
                   5132:                                 } elsif ($curraccess eq 'da') {
                   5133:                                     if (grep(/^da$/,@liveroles)) {
                   5134:                                         push(@possroles,$role);
                   5135:                                     } else {
                   5136:                                         next;
                   5137:                                     }
1.1172.2.89  raeburn  5138:                                 } elsif ($curraccess eq 'status') {
                   5139:                                     if (@okstatus) {
                   5140:                                         if (!@statuses) {
                   5141:                                             if (grep(/^default$/,@okstatus)) {
                   5142:                                                 push(@possroles,$role);
                   5143:                                             }
                   5144:                                         } else {
                   5145:                                             foreach my $status (@okstatus) {
                   5146:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5147:                                                     push(@possroles,$role);
                   5148:                                                     last;
                   5149:                                                 }
                   5150:                                             }
                   5151:                                         }
                   5152:                                     }
                   5153:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5154:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5155:                                         if ($curraccess eq 'exc') {
                   5156:                                             push(@possroles,$role);
                   5157:                                         }
                   5158:                                     } elsif ($curraccess eq 'inc') {
                   5159:                                         push(@possroles,$role);
                   5160:                                     }
                   5161:                                 }
                   5162:                             }
                   5163:                         }
                   5164:                     }
                   5165:                 }
                   5166:             }
                   5167:         }
                   5168:     }
                   5169:     unless (ref($description) eq 'HASH') {
                   5170:         if (ref($roles_by_num) eq 'ARRAY') {
                   5171:             my %desc;
                   5172:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5173:             $description = \%desc;
                   5174:         } else {
                   5175:             $description = {};
                   5176:         }
                   5177:     }
                   5178:     return (\@possroles,$description);
                   5179: }
                   5180: 
1.399     www      5181: # ----------------------------------------------------- Frontpage Announcements
                   5182: #
                   5183: #
                   5184: 
                   5185: sub postannounce {
                   5186:     my ($server,$text)=@_;
1.844     albertel 5187:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5188:     unless ($text=~/\w/) { $text=''; }
                   5189:     return &reply('setannounce:'.&escape($text),$server);
                   5190: }
                   5191: 
                   5192: sub getannounce {
1.448     albertel 5193: 
1.1172.2.96  raeburn  5194:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5195: 	my $announcement='';
1.800     albertel 5196: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5197: 	close($fh);
1.399     www      5198: 	if ($announcement=~/\w/) { 
                   5199: 	    return 
                   5200:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5201:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5202: 	} else {
                   5203: 	    return '';
                   5204: 	}
                   5205:     } else {
                   5206: 	return '';
                   5207:     }
1.351     www      5208: }
1.353     www      5209: 
                   5210: # ---------------------------------------------------------- Course ID routines
                   5211: # Deal with domain's nohist_courseid.db files
                   5212: #
                   5213: 
                   5214: sub courseidput {
1.921     raeburn  5215:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5216:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5217:     my $outcome;
                   5218:     if ($caller eq 'timeonly') {
                   5219:         my $cids = '';
                   5220:         foreach my $item (keys(%$storehash)) {
                   5221:             $cids.=&escape($item).'&';
                   5222:         }
                   5223:         $cids=~s/\&$//;
                   5224:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5225:                           $coursehome);       
                   5226:     } else {
                   5227:         my $items = '';
                   5228:         foreach my $item (keys(%$storehash)) {
                   5229:             $items.= &escape($item).'='.
                   5230:                      &freeze_escape($$storehash{$item}).'&';
                   5231:         }
                   5232:         $items=~s/\&$//;
                   5233:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5234:                           $coursehome);
1.918     raeburn  5235:     }
                   5236:     if ($outcome eq 'unknown_cmd') {
                   5237:         my $what;
                   5238:         foreach my $cid (keys(%$storehash)) {
                   5239:             $what .= &escape($cid).'=';
1.921     raeburn  5240:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5241:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5242:             }
                   5243:             $what =~ s/\:$/&/;
                   5244:         }
                   5245:         $what =~ s/\&$//;  
                   5246:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5247:     } else {
                   5248:         return $outcome;
                   5249:     }
1.353     www      5250: }
                   5251: 
                   5252: sub courseiddump {
1.921     raeburn  5253:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5254:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5255:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5256:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5257:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5258:     my $as_hash = 1;
                   5259:     my %returnhash;
                   5260:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5261:     my %libserv = &all_library();
                   5262:     foreach my $tryserver (keys(%libserv)) {
                   5263:         if ( (  $hostidflag == 1 
                   5264: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5265: 	     || (!defined($hostidflag)) ) {
                   5266: 
1.918     raeburn  5267: 	    if (($domfilter eq '') ||
                   5268: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5269:                 my $rep;
                   5270:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5271:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5272:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5273:                                 &escape($descfilter), &escape($instcodefilter),
                   5274:                                 &escape($ownerfilter), &escape($coursefilter),
                   5275:                                 &escape($typefilter), &escape($regexp_ok),
                   5276:                                 $as_hash, &escape($selfenrollonly),
                   5277:                                 &escape($catfilter), $showhidden, $caller,
                   5278:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5279:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5280:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5281:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5282:                 } else {
                   5283:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5284:                              $sincefilter.':'.&escape($descfilter).':'.
                   5285:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5286:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5287:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5288:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5289:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5290:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5291:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5292:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5293:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5294:                 }
                   5295: 
1.918     raeburn  5296:                 my @pairs=split(/\&/,$rep);
                   5297:                 foreach my $item (@pairs) {
                   5298:                     my ($key,$value)=split(/\=/,$item,2);
                   5299:                     $key = &unescape($key);
                   5300:                     next if ($key =~ /^error: 2 /);
                   5301:                     my $result = &thaw_unescape($value);
                   5302:                     if (ref($result) eq 'HASH') {
                   5303:                         $returnhash{$key}=$result;
                   5304:                     } else {
1.921     raeburn  5305:                         my @responses = split(/:/,$value);
                   5306:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5307:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5308:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5309:                         }
1.1008    raeburn  5310:                     }
1.353     www      5311:                 }
                   5312:             }
                   5313:         }
                   5314:     }
                   5315:     return %returnhash;
                   5316: }
                   5317: 
1.1055    raeburn  5318: sub courselastaccess {
                   5319:     my ($cdom,$cnum,$hostidref) = @_;
                   5320:     my %returnhash;
                   5321:     if ($cdom && $cnum) {
                   5322:         my $chome = &homeserver($cnum,$cdom);
                   5323:         if ($chome ne 'no_host') {
                   5324:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5325:             &extract_lastaccess(\%returnhash,$rep);
                   5326:         }
                   5327:     } else {
                   5328:         if (!$cdom) { $cdom=''; }
                   5329:         my %libserv = &all_library();
                   5330:         foreach my $tryserver (keys(%libserv)) {
                   5331:             if (ref($hostidref) eq 'ARRAY') {
                   5332:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5333:             } 
                   5334:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5335:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5336:                 &extract_lastaccess(\%returnhash,$rep);
                   5337:             }
                   5338:         }
                   5339:     }
                   5340:     return %returnhash;
                   5341: }
                   5342: 
                   5343: sub extract_lastaccess {
                   5344:     my ($returnhash,$rep) = @_;
                   5345:     if (ref($returnhash) eq 'HASH') {
                   5346:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5347:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5348:                  $rep eq '') {
                   5349:             my @pairs=split(/\&/,$rep);
                   5350:             foreach my $item (@pairs) {
                   5351:                 my ($key,$value)=split(/\=/,$item,2);
                   5352:                 $key = &unescape($key);
                   5353:                 next if ($key =~ /^error: 2 /);
                   5354:                 $returnhash->{$key} = &thaw_unescape($value);
                   5355:             }
                   5356:         }
                   5357:     }
                   5358:     return;
                   5359: }
                   5360: 
1.658     raeburn  5361: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5362: 
                   5363: sub dcmailput {
1.685     raeburn  5364:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5365:     my $status = &Apache::lonnet::critical(
1.740     www      5366:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5367:        &escape($message),$server);
1.662     raeburn  5368:     return $status;
                   5369: }
                   5370: 
1.658     raeburn  5371: sub dcmaildump {
                   5372:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5373:     my %returnhash=();
1.846     albertel 5374: 
                   5375:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5376:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5377:                                                          &escape($enddate).':';
                   5378: 	my @esc_senders=map { &escape($_)} @$senders;
                   5379: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5380: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5381:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5382:             if (($key) && ($value)) {
                   5383:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5384:             }
                   5385:         }
                   5386:     }
                   5387:     return %returnhash;
                   5388: }
1.662     raeburn  5389: # ---------------------------------------------------------- Domain roles
                   5390: 
                   5391: sub get_domain_roles {
                   5392:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5393:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5394:         $startdate = '.';
                   5395:     }
1.1018    raeburn  5396:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5397:         $enddate = '.';
                   5398:     }
1.922     raeburn  5399:     my $rolelist;
                   5400:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5401:         $rolelist = join('&',@{$roles});
1.922     raeburn  5402:     }
1.662     raeburn  5403:     my %personnel = ();
1.841     albertel 5404: 
                   5405:     my %servers = &get_servers($dom,'library');
                   5406:     foreach my $tryserver (keys(%servers)) {
                   5407: 	%{$personnel{$tryserver}}=();
                   5408: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5409: 					    &escape($startdate).':'.
                   5410: 					    &escape($enddate).':'.
                   5411: 					    &escape($rolelist), $tryserver))) {
                   5412: 	    my ($key,$value) = split(/\=/,$line,2);
                   5413: 	    if (($key) && ($value)) {
                   5414: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5415: 	    }
                   5416: 	}
1.662     raeburn  5417:     }
                   5418:     return %personnel;
                   5419: }
1.658     raeburn  5420: 
1.1172.2.89  raeburn  5421: sub get_active_domroles {
                   5422:     my ($dom,$roles) = @_;
                   5423:     return () unless (ref($roles) eq 'ARRAY');
                   5424:     my $now = time;
                   5425:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5426:     my %domroles;
                   5427:     foreach my $server (keys(%dompersonnel)) {
                   5428:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5429:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5430:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5431:         }
                   5432:     }
                   5433:     return %domroles;
                   5434: }
                   5435: 
1.1057    www      5436: # ----------------------------------------------------------- Interval timing 
1.149     www      5437: 
1.1153    www      5438: {
                   5439: # Caches needed for speedup of navmaps
                   5440: # We don't want to cache this for very long at all (5 seconds at most)
                   5441: # 
                   5442: # The user for whom we cache
                   5443: my $cachedkey='';
                   5444: # The cached times for this user
                   5445: my %cachedtimes=();
                   5446: # When this was last done
1.1172.2.66  raeburn  5447: my $cachedtime='';
1.1153    www      5448: 
                   5449: sub load_all_first_access {
1.1154    raeburn  5450:     my ($uname,$udom)=@_;
1.1156    www      5451:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5452:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5453:         return;
                   5454:     }
                   5455:     $cachedtime=time;
                   5456:     $cachedkey=$uname.':'.$udom;
                   5457:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5458: }
                   5459: 
1.504     albertel 5460: sub get_first_access {
1.1162    raeburn  5461:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5462:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5463:     if ($argsymb) { $symb=$argsymb; }
                   5464:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5465:     if ($argmap) { $map = $argmap; }
1.926     albertel 5466:     if ($type eq 'course') {
                   5467: 	$res='course';
                   5468:     } elsif ($type eq 'map') {
1.588     albertel 5469: 	$res=&symbread($map);
                   5470:     } else {
                   5471: 	$res=$symb;
                   5472:     }
1.1153    www      5473:     &load_all_first_access($uname,$udom);
                   5474:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5475: }
                   5476: 
                   5477: sub set_first_access {
1.1162    raeburn  5478:     my ($type,$interval)=@_;
1.790     albertel 5479:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5480:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5481:     if ($type eq 'course') {
                   5482: 	$res='course';
                   5483:     } elsif ($type eq 'map') {
1.588     albertel 5484: 	$res=&symbread($map);
                   5485:     } else {
                   5486: 	$res=$symb;
                   5487:     }
1.1153    www      5488:     $cachedkey='';
1.1162    raeburn  5489:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5490:     if ($firstaccess) {
                   5491:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5492:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5493:                  "in $courseid");
                   5494:         return 'already_set';
                   5495:     } else {
1.1162    raeburn  5496:         my $start = time;
                   5497: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5498:                           $udom,$uname);
                   5499:         if ($putres eq 'ok') {
                   5500:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5501:                  $udom,$uname); 
                   5502:             &appenv(
                   5503:                      {
                   5504:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5505:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5506:                      }
                   5507:                   );
1.1172.2.97  raeburn  5508:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5509:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5510:             }
1.1172.2.102  raeburn  5511:         } elsif ($putres ne 'refused') {
                   5512:             &logthis("Result: $putres when attempting to set first access time ".
                   5513:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5514:         }
                   5515:         return $putres;
1.505     albertel 5516:     }
                   5517:     return 'already_set';
1.504     albertel 5518: }
1.1153    www      5519: }
1.1172.2.32  raeburn  5520: 
                   5521: sub checkout {
                   5522:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5523:     my $now=time;
                   5524:     my $lonhost=$perlvar{'lonHostID'};
                   5525:     my $infostr=&escape(
                   5526:                  'CHECKOUTTOKEN&'.
                   5527:                  $tuname.'&'.
                   5528:                  $tudom.'&'.
                   5529:                  $tcrsid.'&'.
                   5530:                  $symb.'&'.
                   5531:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5532:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5533:     if ($token=~/^error\:/) {
                   5534:         &logthis("<font color=\"blue\">WARNING: ".
                   5535:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5536:                  "</font>");
                   5537:         return '';
                   5538:     }
                   5539: 
                   5540:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5541:     $token=~tr/a-z/A-Z/;
                   5542: 
                   5543:     my %infohash=('resource.0.outtoken' => $token,
                   5544:                   'resource.0.checkouttime' => $now,
                   5545:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5546: 
                   5547:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5548:        return '';
                   5549:     } else {
                   5550:         &logthis("<font color=\"blue\">WARNING: ".
                   5551:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5552:                  "</font>");
                   5553:     }
                   5554: 
                   5555:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5556:                          &escape('Checkout '.$infostr.' - '.
                   5557:                                                  $token)) ne 'ok') {
                   5558:         return '';
                   5559:     } else {
                   5560:         &logthis("<font color=\"blue\">WARNING: ".
                   5561:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5562:                  "</font>");
                   5563:     }
                   5564:     return $token;
                   5565: }
                   5566: 
                   5567: # ------------------------------------------------------------ Check in an item
                   5568: 
                   5569: sub checkin {
                   5570:     my $token=shift;
                   5571:     my $now=time;
                   5572:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5573:     $lonhost=~tr/A-Z/a-z/;
                   5574:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5575:     $dtoken=~s/\W/\_/g;
                   5576:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5577:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5578: 
                   5579:     unless (($tuname) && ($tudom)) {
                   5580:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5581:         return '';
                   5582:     }
                   5583: 
                   5584:     unless (&allowed('mgr',$tcrsid)) {
                   5585:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5586:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5587:         return '';
                   5588:     }
                   5589: 
                   5590:     my %infohash=('resource.0.intoken' => $token,
                   5591:                   'resource.0.checkintime' => $now,
                   5592:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5593: 
                   5594:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5595:        return '';
                   5596:     }
                   5597: 
                   5598:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5599:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5600:         return '';
                   5601:     }
                   5602: 
                   5603:     return ($symb,$tuname,$tudom,$tcrsid);
                   5604: }
                   5605: 
1.110     www      5606: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5607: 
                   5608: sub expirespread {
                   5609:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5610:     my $cid=$env{'request.course.id'}; 
1.110     www      5611:     if ($cid) {
                   5612:        my $now=time;
                   5613:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5614:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5615:                             $env{'course.'.$cid.'.num'}.
1.110     www      5616: 	        	    ':nohist_expirationdates:'.
                   5617:                             &escape($key).'='.$now,
1.620     albertel 5618:                             $env{'course.'.$cid.'.home'})
1.110     www      5619:     }
                   5620:     return 'ok';
1.14      www      5621: }
                   5622: 
1.109     www      5623: # ----------------------------------------------------- Devalidate Spreadsheets
                   5624: 
                   5625: sub devalidate {
1.325     www      5626:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5627:     my $cid=$env{'request.course.id'}; 
1.109     www      5628:     if ($cid) {
1.391     matthew  5629:         # delete the stored spreadsheets for
                   5630:         # - the student level sheet of this user in course's homespace
                   5631:         # - the assessment level sheet for this resource 
                   5632:         #   for this user in user's homespace
1.553     albertel 5633: 	# - current conditional state info
1.325     www      5634: 	my $key=$uname.':'.$udom.':';
1.109     www      5635:         my $status=
1.299     matthew  5636: 	    &del('nohist_calculatedsheets',
1.391     matthew  5637: 		 [$key.'studentcalc:'],
1.620     albertel 5638: 		 $env{'course.'.$cid.'.domain'},
                   5639: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5640: 		.' '.
                   5641: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5642: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5643:         unless ($status eq 'ok ok') {
                   5644:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5645:                     $uname.' at '.$udom.' for '.
1.109     www      5646: 		    $symb.': '.$status);
1.133     albertel 5647:         }
1.553     albertel 5648: 	&delenv('user.state.'.$cid);
1.109     www      5649:     }
                   5650: }
                   5651: 
1.265     albertel 5652: sub get_scalar {
                   5653:     my ($string,$end) = @_;
                   5654:     my $value;
                   5655:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5656: 	$value = $1;
                   5657:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5658: 	$value = $1;
                   5659:     }
                   5660:     return &unescape($value);
                   5661: }
                   5662: 
                   5663: sub array2str {
                   5664:   my (@array) = @_;
                   5665:   my $result=&arrayref2str(\@array);
                   5666:   $result=~s/^__ARRAY_REF__//;
                   5667:   $result=~s/__END_ARRAY_REF__$//;
                   5668:   return $result;
                   5669: }
                   5670: 
1.204     albertel 5671: sub arrayref2str {
                   5672:   my ($arrayref) = @_;
1.265     albertel 5673:   my $result='__ARRAY_REF__';
1.204     albertel 5674:   foreach my $elem (@$arrayref) {
1.265     albertel 5675:     if(ref($elem) eq 'ARRAY') {
                   5676:       $result.=&arrayref2str($elem).'&';
                   5677:     } elsif(ref($elem) eq 'HASH') {
                   5678:       $result.=&hashref2str($elem).'&';
                   5679:     } elsif(ref($elem)) {
                   5680:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5681:     } else {
                   5682:       $result.=&escape($elem).'&';
                   5683:     }
                   5684:   }
                   5685:   $result=~s/\&$//;
1.265     albertel 5686:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5687:   return $result;
                   5688: }
                   5689: 
1.168     albertel 5690: sub hash2str {
1.204     albertel 5691:   my (%hash) = @_;
                   5692:   my $result=&hashref2str(\%hash);
1.265     albertel 5693:   $result=~s/^__HASH_REF__//;
                   5694:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5695:   return $result;
                   5696: }
                   5697: 
                   5698: sub hashref2str {
                   5699:   my ($hashref)=@_;
1.265     albertel 5700:   my $result='__HASH_REF__';
1.800     albertel 5701:   foreach my $key (sort(keys(%$hashref))) {
                   5702:     if (ref($key) eq 'ARRAY') {
                   5703:       $result.=&arrayref2str($key).'=';
                   5704:     } elsif (ref($key) eq 'HASH') {
                   5705:       $result.=&hashref2str($key).'=';
                   5706:     } elsif (ref($key)) {
1.265     albertel 5707:       $result.='=';
1.800     albertel 5708:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5709:     } else {
1.1132    raeburn  5710: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5711:     }
                   5712: 
1.800     albertel 5713:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5714:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5715:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5716:       $result.=&hashref2str($hashref->{$key}).'&';
                   5717:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5718:        $result.='&';
1.800     albertel 5719:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5720:     } else {
1.800     albertel 5721:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5722:     }
                   5723:   }
1.168     albertel 5724:   $result=~s/\&$//;
1.265     albertel 5725:   $result .= '__END_HASH_REF__';
1.168     albertel 5726:   return $result;
                   5727: }
                   5728: 
                   5729: sub str2hash {
1.265     albertel 5730:     my ($string)=@_;
                   5731:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5732:     return %$hash;
                   5733: }
                   5734: 
                   5735: sub str2hashref {
1.168     albertel 5736:   my ($string) = @_;
1.265     albertel 5737: 
                   5738:   my %hash;
                   5739: 
                   5740:   if($string !~ /^__HASH_REF__/) {
                   5741:       if (! ($string eq '' || !defined($string))) {
                   5742: 	  $hash{'error'}='Not hash reference';
                   5743:       }
                   5744:       return (\%hash, $string);
                   5745:   }
                   5746: 
                   5747:   $string =~ s/^__HASH_REF__//;
                   5748: 
                   5749:   while($string !~ /^__END_HASH_REF__/) {
                   5750:       #key
                   5751:       my $key='';
                   5752:       if($string =~ /^__HASH_REF__/) {
                   5753:           ($key, $string)=&str2hashref($string);
                   5754:           if(defined($key->{'error'})) {
                   5755:               $hash{'error'}='Bad data';
                   5756:               return (\%hash, $string);
                   5757:           }
                   5758:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5759:           ($key, $string)=&str2arrayref($string);
                   5760:           if($key->[0] eq 'Array reference error') {
                   5761:               $hash{'error'}='Bad data';
                   5762:               return (\%hash, $string);
                   5763:           }
                   5764:       } else {
                   5765:           $string =~ s/^(.*?)=//;
1.267     albertel 5766: 	  $key=&unescape($1);
1.265     albertel 5767:       }
                   5768:       $string =~ s/^=//;
                   5769: 
                   5770:       #value
                   5771:       my $value='';
                   5772:       if($string =~ /^__HASH_REF__/) {
                   5773:           ($value, $string)=&str2hashref($string);
                   5774:           if(defined($value->{'error'})) {
                   5775:               $hash{'error'}='Bad data';
                   5776:               return (\%hash, $string);
                   5777:           }
                   5778:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5779:           ($value, $string)=&str2arrayref($string);
                   5780:           if($value->[0] eq 'Array reference error') {
                   5781:               $hash{'error'}='Bad data';
                   5782:               return (\%hash, $string);
                   5783:           }
                   5784:       } else {
                   5785: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5786:       }
                   5787:       $string =~ s/^&//;
                   5788: 
                   5789:       $hash{$key}=$value;
1.204     albertel 5790:   }
1.265     albertel 5791: 
                   5792:   $string =~ s/^__END_HASH_REF__//;
                   5793: 
                   5794:   return (\%hash, $string);
1.204     albertel 5795: }
                   5796: 
                   5797: sub str2array {
1.265     albertel 5798:     my ($string)=@_;
                   5799:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5800:     return @$array;
                   5801: }
                   5802: 
                   5803: sub str2arrayref {
1.204     albertel 5804:   my ($string) = @_;
1.265     albertel 5805:   my @array;
                   5806: 
                   5807:   if($string !~ /^__ARRAY_REF__/) {
                   5808:       if (! ($string eq '' || !defined($string))) {
                   5809: 	  $array[0]='Array reference error';
                   5810:       }
                   5811:       return (\@array, $string);
                   5812:   }
                   5813: 
                   5814:   $string =~ s/^__ARRAY_REF__//;
                   5815: 
                   5816:   while($string !~ /^__END_ARRAY_REF__/) {
                   5817:       my $value='';
                   5818:       if($string =~ /^__HASH_REF__/) {
                   5819:           ($value, $string)=&str2hashref($string);
                   5820:           if(defined($value->{'error'})) {
                   5821:               $array[0] ='Array reference error';
                   5822:               return (\@array, $string);
                   5823:           }
                   5824:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5825:           ($value, $string)=&str2arrayref($string);
                   5826:           if($value->[0] eq 'Array reference error') {
                   5827:               $array[0] ='Array reference error';
                   5828:               return (\@array, $string);
                   5829:           }
                   5830:       } else {
                   5831: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5832:       }
                   5833:       $string =~ s/^&//;
                   5834: 
                   5835:       push(@array, $value);
1.191     harris41 5836:   }
1.265     albertel 5837: 
                   5838:   $string =~ s/^__END_ARRAY_REF__//;
                   5839: 
                   5840:   return (\@array, $string);
1.168     albertel 5841: }
                   5842: 
1.167     albertel 5843: # -------------------------------------------------------------------Temp Store
                   5844: 
1.168     albertel 5845: sub tmpreset {
                   5846:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5847:   if (!$symb) {
                   5848:     $symb=&symbread();
1.620     albertel 5849:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5850:   }
                   5851:   $symb=escape($symb);
                   5852: 
1.620     albertel 5853:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5854:   $namespace=~s/\//\_/g;
                   5855:   $namespace=~s/\W//g;
                   5856: 
1.620     albertel 5857:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5858:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5859:   if ($domain eq 'public' && $stuname eq 'public') {
                   5860:       $stuname=$ENV{'REMOTE_ADDR'};
                   5861:   }
1.1117    foxr     5862:   my $path=LONCAPA::tempdir();
1.168     albertel 5863:   my %hash;
                   5864:   if (tie(%hash,'GDBM_File',
                   5865: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5866: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5867:     foreach my $key (keys(%hash)) {
1.180     albertel 5868:       if ($key=~ /:$symb/) {
1.168     albertel 5869: 	delete($hash{$key});
                   5870:       }
                   5871:     }
                   5872:   }
                   5873: }
                   5874: 
1.167     albertel 5875: sub tmpstore {
1.168     albertel 5876:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5877: 
                   5878:   if (!$symb) {
                   5879:     $symb=&symbread();
1.620     albertel 5880:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5881:   }
                   5882:   $symb=escape($symb);
                   5883: 
                   5884:   if (!$namespace) {
                   5885:     # I don't think we would ever want to store this for a course.
                   5886:     # it seems this will only be used if we don't have a course.
1.620     albertel 5887:     #$namespace=$env{'request.course.id'};
1.168     albertel 5888:     #if (!$namespace) {
1.620     albertel 5889:       $namespace=$env{'request.state'};
1.168     albertel 5890:     #}
                   5891:   }
                   5892:   $namespace=~s/\//\_/g;
                   5893:   $namespace=~s/\W//g;
1.620     albertel 5894:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5895:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5896:   if ($domain eq 'public' && $stuname eq 'public') {
                   5897:       $stuname=$ENV{'REMOTE_ADDR'};
                   5898:   }
1.168     albertel 5899:   my $now=time;
                   5900:   my %hash;
1.1117    foxr     5901:   my $path=LONCAPA::tempdir();
1.168     albertel 5902:   if (tie(%hash,'GDBM_File',
                   5903: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5904: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5905:     $hash{"version:$symb"}++;
                   5906:     my $version=$hash{"version:$symb"};
                   5907:     my $allkeys=''; 
                   5908:     foreach my $key (keys(%$storehash)) {
                   5909:       $allkeys.=$key.':';
1.591     albertel 5910:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5911:     }
                   5912:     $hash{"$version:$symb:timestamp"}=$now;
                   5913:     $allkeys.='timestamp';
                   5914:     $hash{"$version:keys:$symb"}=$allkeys;
                   5915:     if (untie(%hash)) {
                   5916:       return 'ok';
                   5917:     } else {
                   5918:       return "error:$!";
                   5919:     }
                   5920:   } else {
                   5921:     return "error:$!";
                   5922:   }
                   5923: }
1.167     albertel 5924: 
1.168     albertel 5925: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5926: 
1.168     albertel 5927: sub tmprestore {
                   5928:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5929: 
1.168     albertel 5930:   if (!$symb) {
                   5931:     $symb=&symbread();
1.620     albertel 5932:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5933:   }
                   5934:   $symb=escape($symb);
                   5935: 
1.620     albertel 5936:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5937: 
1.620     albertel 5938:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5939:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5940:   if ($domain eq 'public' && $stuname eq 'public') {
                   5941:       $stuname=$ENV{'REMOTE_ADDR'};
                   5942:   }
1.168     albertel 5943:   my %returnhash;
                   5944:   $namespace=~s/\//\_/g;
                   5945:   $namespace=~s/\W//g;
                   5946:   my %hash;
1.1117    foxr     5947:   my $path=LONCAPA::tempdir();
1.168     albertel 5948:   if (tie(%hash,'GDBM_File',
                   5949: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5950: 	  &GDBM_READER(),0640)) {
1.168     albertel 5951:     my $version=$hash{"version:$symb"};
                   5952:     $returnhash{'version'}=$version;
                   5953:     my $scope;
                   5954:     for ($scope=1;$scope<=$version;$scope++) {
                   5955:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5956:       my @keys=split(/:/,$vkeys);
                   5957:       my $key;
                   5958:       $returnhash{"$scope:keys"}=$vkeys;
                   5959:       foreach $key (@keys) {
1.591     albertel 5960: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5961: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5962:       }
                   5963:     }
1.168     albertel 5964:     if (!(untie(%hash))) {
                   5965:       return "error:$!";
                   5966:     }
                   5967:   } else {
                   5968:     return "error:$!";
                   5969:   }
                   5970:   return %returnhash;
1.167     albertel 5971: }
                   5972: 
1.9       www      5973: # ----------------------------------------------------------------------- Store
                   5974: 
                   5975: sub store {
1.1172.2.64  raeburn  5976:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5977:     my $home='';
                   5978: 
1.168     albertel 5979:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5980: 
1.213     www      5981:     $symb=&symbclean($symb);
1.122     albertel 5982:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5983: 
1.620     albertel 5984:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5985:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5986: 
                   5987:     &devalidate($symb,$stuname,$domain);
1.109     www      5988: 
                   5989:     $symb=escape($symb);
1.187     www      5990:     if (!$namespace) { 
1.620     albertel 5991:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5992:           return ''; 
                   5993:        } 
                   5994:     }
1.620     albertel 5995:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5996: 
                   5997:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5998:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5999: 
1.12      www      6000:     my $namevalue='';
1.800     albertel 6001:     foreach my $key (keys(%$storehash)) {
                   6002:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6003:     }
1.12      www      6004:     $namevalue=~s/\&$//;
1.187     www      6005:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6006:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6007: }
                   6008: 
1.47      www      6009: # -------------------------------------------------------------- Critical Store
                   6010: 
                   6011: sub cstore {
1.1172.2.64  raeburn  6012:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6013:     my $home='';
                   6014: 
1.168     albertel 6015:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6016: 
1.213     www      6017:     $symb=&symbclean($symb);
1.122     albertel 6018:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6019: 
1.620     albertel 6020:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6021:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6022: 
                   6023:     &devalidate($symb,$stuname,$domain);
1.109     www      6024: 
                   6025:     $symb=escape($symb);
1.187     www      6026:     if (!$namespace) { 
1.620     albertel 6027:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6028:           return ''; 
                   6029:        } 
                   6030:     }
1.620     albertel 6031:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6032: 
                   6033:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6034:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6035: 
1.47      www      6036:     my $namevalue='';
1.800     albertel 6037:     foreach my $key (keys(%$storehash)) {
                   6038:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6039:     }
1.47      www      6040:     $namevalue=~s/\&$//;
1.187     www      6041:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6042:     return critical
1.1172.2.64  raeburn  6043:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6044: }
                   6045: 
1.9       www      6046: # --------------------------------------------------------------------- Restore
                   6047: 
                   6048: sub restore {
1.124     www      6049:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6050:     my $home='';
                   6051: 
1.168     albertel 6052:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6053: 
1.122     albertel 6054:     if (!$symb) {
1.1172.2.26  raeburn  6055:         return if ($namespace eq 'courserequests');
                   6056:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6057:     } else {
1.1172.2.26  raeburn  6058:         unless ($namespace eq 'courserequests') {
                   6059:             $symb=&escape(&symbclean($symb));
                   6060:         }
1.122     albertel 6061:     }
1.188     www      6062:     if (!$namespace) { 
1.620     albertel 6063:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6064:           return ''; 
                   6065:        } 
                   6066:     }
1.620     albertel 6067:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6068:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6069:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6070:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6071: 
1.12      www      6072:     my %returnhash=();
1.800     albertel 6073:     foreach my $line (split(/\&/,$answer)) {
                   6074: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6075:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6076:     }
1.75      www      6077:     my $version;
                   6078:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6079:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6080:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6081:        }
1.75      www      6082:     }
1.13      www      6083:     return %returnhash;
1.34      www      6084: }
                   6085: 
                   6086: # ---------------------------------------------------------- Course Description
1.1118    foxr     6087: #
                   6088: #  
1.34      www      6089: 
                   6090: sub coursedescription {
1.731     albertel 6091:     my ($courseid,$args)=@_;
1.34      www      6092:     $courseid=~s/^\///;
1.49      www      6093:     $courseid=~s/\_/\//g;
1.34      www      6094:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6095:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6096:     my $normalid=$cdomain.'_'.$cnum;
                   6097:     # need to always cache even if we get errors otherwise we keep 
                   6098:     # trying and trying and trying to get the course description.
                   6099:     my %envhash=();
                   6100:     my %returnhash=();
1.731     albertel 6101:     
                   6102:     my $expiretime=600;
                   6103:     if ($env{'request.course.id'} eq $normalid) {
                   6104: 	$expiretime=120;
                   6105:     }
                   6106: 
                   6107:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6108:     if (!$args->{'freshen_cache'}
                   6109: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6110: 	foreach my $key (keys(%env)) {
                   6111: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6112: 	    my ($setting) = $1;
                   6113: 	    $returnhash{$setting} = $env{$key};
                   6114: 	}
                   6115: 	return %returnhash;
                   6116:     }
                   6117: 
1.1118    foxr     6118:     # get the data again
                   6119: 
1.731     albertel 6120:     if (!$args->{'one_time'}) {
                   6121: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6122:     }
1.811     albertel 6123: 
1.34      www      6124:     if ($chome ne 'no_host') {
1.302     albertel 6125:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6126:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6127: 	   my $username = $env{'user.name'}; # Defult username
                   6128: 	   if(defined $args->{'user'}) {
                   6129: 	       $username = $args->{'user'};
                   6130: 	   }
1.129     albertel 6131:            $returnhash{'home'}= $chome;
                   6132: 	   $returnhash{'domain'} = $cdomain;
                   6133: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6134:            if (!defined($returnhash{'type'})) {
                   6135:                $returnhash{'type'} = 'Course';
                   6136:            }
1.130     albertel 6137:            while (my ($name,$value) = each %returnhash) {
1.53      www      6138:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6139:            }
1.270     www      6140:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6141:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6142: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6143:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6144:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6145:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6146:        }
                   6147:     }
1.731     albertel 6148:     if (!$args->{'one_time'}) {
1.949     raeburn  6149: 	&appenv(\%envhash);
1.731     albertel 6150:     }
1.302     albertel 6151:     return %returnhash;
1.461     www      6152: }
                   6153: 
1.1080    raeburn  6154: sub update_released_required {
                   6155:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6156:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6157:         $cid = $env{'request.course.id'};
                   6158:         $cdom = $env{'course.'.$cid.'.domain'};
                   6159:         $cnum = $env{'course.'.$cid.'.num'};
                   6160:         $chome = $env{'course.'.$cid.'.home'};
                   6161:     }
                   6162:     if ($needsrelease) {
                   6163:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6164:         my $needsupdate;
                   6165:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6166:             $needsupdate = 1;
                   6167:         } else {
                   6168:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6169:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6170:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6171:                 $needsupdate = 1;
                   6172:             }
                   6173:         }
                   6174:         if ($needsupdate) {
                   6175:             my %needshash = (
                   6176:                              'internal.releaserequired' => $needsrelease,
                   6177:                             );
                   6178:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6179:             if ($putresult eq 'ok') {
                   6180:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6181:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6182:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6183:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6184:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6185:                 }
                   6186:             }
                   6187:         }
                   6188:     }
                   6189:     return;
                   6190: }
                   6191: 
1.461     www      6192: # -------------------------------------------------See if a user is privileged
                   6193: 
                   6194: sub privileged {
1.1172.2.23  raeburn  6195:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6196:     my $now = time;
1.1172.2.23  raeburn  6197:     my $roles;
                   6198:     if (ref($possroles) eq 'ARRAY') {
                   6199:         $roles = $possroles;
                   6200:     } else {
                   6201:         $roles = ['dc','su'];
                   6202:     }
                   6203:     if (ref($possdomains) eq 'ARRAY') {
                   6204:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6205:         foreach my $dom (@{$possdomains}) {
                   6206:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6207:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6208:                 foreach my $role (@{$roles}) {
                   6209:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6210:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6211:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6212:                             return 1 unless (($end && $end < $now) ||
                   6213:                                              ($start && $start > $now));
                   6214:                         }
                   6215:                     }
                   6216:                 }
                   6217:             }
                   6218:         }
                   6219:     } else {
                   6220:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6221:         my $now = time;
1.1170    droeschl 6222: 
1.1172.2.58  raeburn  6223:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6224:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6225:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6226:                 return 1 unless ($tend && $tend < $now)
                   6227:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6228:             }
1.1172.2.23  raeburn  6229:         }
                   6230:     }
1.461     www      6231:     return 0;
1.9       www      6232: }
1.1       albertel 6233: 
1.1172.2.23  raeburn  6234: sub privileged_by_domain {
                   6235:     my ($domains,$roles) = @_;
                   6236:     my %privileged = ();
                   6237:     my $cachetime = 60*60*24;
                   6238:     my $now = time;
                   6239:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6240:         return %privileged;
                   6241:     }
                   6242:     foreach my $dom (@{$domains}) {
                   6243:         next if (ref($privileged{$dom}) eq 'HASH');
                   6244:         my $needroles;
                   6245:         foreach my $role (@{$roles}) {
                   6246:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6247:             if (defined($cached)) {
                   6248:                 if (ref($result) eq 'HASH') {
                   6249:                     $privileged{$dom}{$role} = $result;
                   6250:                 }
                   6251:             } else {
                   6252:                 $needroles = 1;
                   6253:             }
                   6254:         }
                   6255:         if ($needroles) {
                   6256:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6257:             $privileged{$dom} = {};
                   6258:             foreach my $server (keys(%dompersonnel)) {
                   6259:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6260:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6261:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6262:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6263:                         next if ($end && $end < $now);
                   6264:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6265:                             $dompersonnel{$server}{$item};
                   6266:                     }
                   6267:                 }
                   6268:             }
                   6269:             if (ref($privileged{$dom}) eq 'HASH') {
                   6270:                 foreach my $role (@{$roles}) {
                   6271:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6272:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6273:                     } else {
                   6274:                         my %hash = ();
                   6275:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6276:                     }
                   6277:                 }
                   6278:             }
                   6279:         }
                   6280:     }
                   6281:     return %privileged;
                   6282: }
                   6283: 
1.103     harris41 6284: # -------------------------------------------------------- Get user privileges
1.11      www      6285: 
                   6286: sub rolesinit {
1.1169    droeschl 6287:     my ($domain, $username) = @_;
                   6288:     my %userroles = ('user.login.time' => time);
                   6289:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6290: 
                   6291:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6292:     # also, blocking can be triggered by an activating timer
                   6293:     # it's saved in the user's %env.
                   6294:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6295:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6296:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6297:         %timerintchk, %timerintenv);
                   6298: 
1.1162    raeburn  6299:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6300:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6301:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6302:     }
1.1169    droeschl 6303: 
1.1162    raeburn  6304:     foreach my $key (keys(%timerinterval)) {
                   6305:         my ($cid,$rest) = split(/\0/,$key);
                   6306:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6307:     }
1.1169    droeschl 6308: 
1.11      www      6309:     my %allroles=();
1.1162    raeburn  6310:     my %allgroups=();
1.11      www      6311: 
1.1172.2.58  raeburn  6312:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6313:         my $role = $rolesdump{$area};
                   6314:         $area =~ s/\_\w\w$//;
                   6315: 
                   6316:         my ($trole, $tend, $tstart, $group_privs);
                   6317: 
                   6318:         if ($role =~ /^cr/) {
                   6319:         # Custom role, defined by a user 
                   6320:         # e.g., user.role.cr/msu/smith/mynewrole
                   6321:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6322:                 $trole = $1;
                   6323:                 ($tend, $tstart) = split('_', $2);
                   6324:             } else {
                   6325:                 $trole = $role;
                   6326:             }
                   6327:         } elsif ($role =~ m|^gr/|) {
                   6328:         # Role of member in a group, defined within a course/community
                   6329:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6330:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6331:             next if $tstart eq '-1';
                   6332:             ($trole, $group_privs) = split(/\//, $trole);
                   6333:             $group_privs = &unescape($group_privs);
                   6334:         } else {
                   6335:         # Just a normal role, defined in roles.tab
                   6336:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6337:         }
                   6338: 
                   6339:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6340:                  $username);
                   6341:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6342: 
                   6343:         # role expired or not available yet?
                   6344:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6345:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6346: 
                   6347:         next if $area eq '' or $trole eq '';
                   6348: 
                   6349:         my $spec = "$trole.$area";
                   6350:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6351: 
                   6352:         if ($trole =~ /^cr\//) {
                   6353:         # Custom role, defined by a user
                   6354:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6355:         } elsif ($trole eq 'gr') {
                   6356:         # Role of a member in a group, defined within a course/community
                   6357:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6358:             next;
                   6359:         } else {
                   6360:         # Normal role, defined in roles.tab
                   6361:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6362:         }
                   6363: 
                   6364:         my $cid = $tdomain.'_'.$trest;
                   6365:         unless ($firstaccchk{$cid}) {
                   6366:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6367:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6368:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6369:                         $coursetimerstarts{$cid}{$item}; 
                   6370:                 }
                   6371:             }
                   6372:             $firstaccchk{$cid} = 1;
                   6373:         }
                   6374:         unless ($timerintchk{$cid}) {
                   6375:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6376:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6377:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6378:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6379:                 }
1.12      www      6380:             }
1.1169    droeschl 6381:             $timerintchk{$cid} = 1;
1.191     harris41 6382:         }
1.11      www      6383:     }
1.1169    droeschl 6384: 
1.1172.2.91  raeburn  6385:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6386:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6387:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6388:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6389: 
1.1162    raeburn  6390:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6391: }
                   6392: 
1.567     raeburn  6393: sub set_arearole {
1.1172.2.19  raeburn  6394:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6395:     unless ($nolog) {
1.567     raeburn  6396: # log the associated role with the area
1.1172.2.19  raeburn  6397:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6398:     }
1.743     albertel 6399:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6400: }
                   6401: 
                   6402: sub custom_roleprivs {
                   6403:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6404:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6405:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6406:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6407:         my ($rdummy,$roledef)=
                   6408:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6409:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6410:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6411:             if (defined($syspriv)) {
1.1043    raeburn  6412:                 if ($trest =~ /^$match_community$/) {
                   6413:                     $syspriv =~ s/bre\&S//; 
                   6414:                 }
1.567     raeburn  6415:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6416:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6417:             }
                   6418:             if ($tdomain ne '') {
                   6419:                 if (defined($dompriv)) {
                   6420:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6421:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6422:                 }
                   6423:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6424:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6425:                         my $rolename = $1;
                   6426:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6427:                     }
1.567     raeburn  6428:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6429:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6430:                 }
                   6431:             }
                   6432:         }
                   6433:     }
                   6434: }
                   6435: 
1.1172.2.89  raeburn  6436: sub course_adhocrole_privs {
                   6437:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6438:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6439:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6440:         my (%currprivs,%storeprivs);
                   6441:         foreach my $item (split(/:/,$coursepriv)) {
                   6442:             my ($priv,$restrict) = split(/\&/,$item);
                   6443:             $currprivs{$priv} = $restrict;
                   6444:         }
                   6445:         my (%possadd,%possremove,%full);
                   6446:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6447:             my ($priv,$restrict)=split(/\&/,$item);
                   6448:             $full{$priv} = $restrict;
                   6449:         }
                   6450:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6451:              next if ($item eq '');
                   6452:              my ($rule,$rest) = split(/=/,$item);
                   6453:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6454:              foreach my $priv (split(/:/,$rest)) {
                   6455:                  if ($priv ne '') {
                   6456:                      if ($rule eq 'off') {
                   6457:                          $possremove{$priv} = 1;
                   6458:                      } else {
                   6459:                          $possadd{$priv} = 1;
                   6460:                      }
                   6461:                  }
                   6462:              }
                   6463:          }
                   6464:          foreach my $priv (sort(keys(%full))) {
                   6465:              if (exists($currprivs{$priv})) {
                   6466:                  unless (exists($possremove{$priv})) {
                   6467:                      $storeprivs{$priv} = $currprivs{$priv};
                   6468:                  }
                   6469:              } elsif (exists($possadd{$priv})) {
                   6470:                  $storeprivs{$priv} = $full{$priv};
                   6471:              }
                   6472:          }
                   6473:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6474:      }
                   6475:      return $coursepriv;
                   6476: }
                   6477: 
1.678     raeburn  6478: sub group_roleprivs {
                   6479:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6480:     my $access = 1;
                   6481:     my $now = time;
                   6482:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6483:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6484:     if ($access) {
1.811     albertel 6485:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6486:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6487:     }
                   6488: }
1.567     raeburn  6489: 
                   6490: sub standard_roleprivs {
                   6491:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6492:     if (defined($pr{$trole.':s'})) {
                   6493:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6494:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6495:     }
                   6496:     if ($tdomain ne '') {
                   6497:         if (defined($pr{$trole.':d'})) {
                   6498:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6499:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6500:         }
                   6501:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6502:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6503:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6504:         }
                   6505:     }
                   6506: }
                   6507: 
                   6508: sub set_userprivs {
1.1064    raeburn  6509:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6510:     my $author=0;
                   6511:     my $adv=0;
1.1172.2.91  raeburn  6512:     my $rar=0;
1.678     raeburn  6513:     my %grouproles = ();
                   6514:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6515:         my @groupkeys; 
1.1000    raeburn  6516:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6517:             push(@groupkeys,$role);
                   6518:         }
                   6519:         if (ref($groups_roles) eq 'HASH') {
                   6520:             foreach my $key (keys(%{$groups_roles})) {
                   6521:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6522:                     push(@groupkeys,$key);
                   6523:                 }
                   6524:             }
                   6525:         }
                   6526:         if (@groupkeys > 0) {
                   6527:             foreach my $role (@groupkeys) {
                   6528:                 my ($trole,$area,$sec,$extendedarea);
                   6529:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6530:                     $trole = $1;
                   6531:                     $area = $2;
                   6532:                     $sec = $3;
                   6533:                     $extendedarea = $area.$sec;
                   6534:                     if (exists($$allgroups{$area})) {
                   6535:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6536:                             my $spec = $trole.'.'.$extendedarea;
                   6537:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6538:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6539:                         }
1.678     raeburn  6540:                     }
                   6541:                 }
                   6542:             }
                   6543:         }
                   6544:     }
1.800     albertel 6545:     foreach my $group (keys(%grouproles)) {
                   6546:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6547:     }
1.800     albertel 6548:     foreach my $role (keys(%{$allroles})) {
                   6549:         my %thesepriv;
1.941     raeburn  6550:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6551:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6552:             if ($item ne '') {
                   6553:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6554:                 if ($restrictions eq '') {
                   6555:                     $thesepriv{$privilege}='F';
                   6556:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6557:                     $thesepriv{$privilege}.=$restrictions;
                   6558:                 }
                   6559:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6560:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6561:             }
                   6562:         }
                   6563:         my $thesestr='';
1.1104    raeburn  6564:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6565: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6566: 	}
                   6567:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6568:     }
1.1172.2.91  raeburn  6569:     return ($author,$adv,$rar);
1.567     raeburn  6570: }
                   6571: 
1.994     raeburn  6572: sub role_status {
1.1104    raeburn  6573:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6574:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6575:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6576:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6577:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6578:             $$where = '/'.$two;
1.994     raeburn  6579:             $$trolecode=$$role.'.'.$$where;
                   6580:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6581:             $$tstatus='is';
1.1104    raeburn  6582:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6583:                 $$tstatus='future';
1.1034    raeburn  6584:                 if ($$tstart<$now) {
                   6585:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6586:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6587:                             my (%allroles,%allgroups,$group_privs,
                   6588:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6589:                             my %userroles = (
                   6590:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6591:                             );
1.1064    raeburn  6592:                             @rolecodes = ('cm'); 
1.1002    raeburn  6593:                             my $spec=$$role.'.'.$$where;
                   6594:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6595:                             if ($$role =~ /^cr\//) {
                   6596:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6597:                                 push(@rolecodes,'cr');
1.1002    raeburn  6598:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6599:                                 push(@rolecodes,$$role);
1.1002    raeburn  6600:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6601:                                                     $env{'user.name'});
1.1064    raeburn  6602:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6603:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6604:                                 $group_privs = &unescape($group_privs);
                   6605:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6606:                                 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  6607:                                 &get_groups_roles($tdomain,$trest,
                   6608:                                                   \%course_roles,\@rolecodes,
                   6609:                                                   \%groups_roles);
1.1002    raeburn  6610:                             } else {
1.1064    raeburn  6611:                                 push(@rolecodes,$$role);
1.1002    raeburn  6612:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6613:                             }
1.1172.2.91  raeburn  6614:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6615:                                                                    \%groups_roles);
1.1064    raeburn  6616:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6617:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6618:                         }
                   6619:                     }
1.1034    raeburn  6620:                     $$tstatus = 'is';
1.1002    raeburn  6621:                 }
1.994     raeburn  6622:             }
                   6623:             if ($$tend) {
1.1104    raeburn  6624:                 if ($$tend<$update) {
1.994     raeburn  6625:                     $$tstatus='expired';
                   6626:                 } elsif ($$tend<$now) {
                   6627:                     $$tstatus='will_not';
                   6628:                 }
                   6629:             }
                   6630:         }
                   6631:     }
                   6632: }
                   6633: 
1.1104    raeburn  6634: sub get_groups_roles {
                   6635:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6636:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6637:                   (ref($rolecodes) eq 'ARRAY') && 
                   6638:                   (ref($groups_roles) eq 'HASH')); 
                   6639:     if (keys(%{$cdom_courseroles}) > 0) {
                   6640:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6641:         if ($cdom ne '' && $cnum ne '') {
                   6642:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6643:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6644:                     my $crsrole = $1;
                   6645:                     my $crssec = $2;
                   6646:                     if ($crsrole =~ /^cr/) {
                   6647:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6648:                             push(@{$rolecodes},'cr');
                   6649:                         }
                   6650:                     } else {
                   6651:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6652:                             push(@{$rolecodes},$crsrole);
                   6653:                         }
                   6654:                     }
                   6655:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6656:                     if ($crssec ne '') {
                   6657:                         $rolekey .= "/$crssec";
                   6658:                     }
                   6659:                     $rolekey .= './';
                   6660:                     $groups_roles->{$rolekey} = $rolecodes;
                   6661:                 }
                   6662:             }
                   6663:         }
                   6664:     }
                   6665:     return;
                   6666: }
                   6667: 
                   6668: sub delete_env_groupprivs {
                   6669:     my ($where,$courseroles,$possroles) = @_;
                   6670:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6671:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6672:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6673:         %{$courseroles->{$udom}} =
                   6674:             &get_my_roles('','','userroles',['active'],
                   6675:                           $possroles,[$udom],1);
                   6676:     }
                   6677:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6678:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6679:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6680:             my $area = '/'.$cdom.'/'.$cnum;
                   6681:             my $privkey = "user.priv.$crsrole.$area";
                   6682:             if ($crssec ne '') {
                   6683:                 $privkey .= '/'.$crssec;
                   6684:             }
                   6685:             $privkey .= ".$area/$group";
                   6686:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6687:         }
                   6688:     }
                   6689:     return;
                   6690: }
                   6691: 
1.994     raeburn  6692: sub check_adhoc_privs {
1.1172.2.86  raeburn  6693:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6694:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6695:     if ($sec) {
                   6696:         $cckey .= '/'.$sec;
                   6697:     }
1.1172.2.9  raeburn  6698:     my $setprivs;
1.994     raeburn  6699:     if ($env{$cckey}) {
                   6700:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6701:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6702:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6703:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6704:             $setprivs = 1;
1.994     raeburn  6705:         }
                   6706:     } else {
1.1172.2.87  raeburn  6707:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6708:         $setprivs = 1;
1.994     raeburn  6709:     }
1.1172.2.9  raeburn  6710:     return $setprivs;
1.994     raeburn  6711: }
                   6712: 
                   6713: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6714: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6715:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6716:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6717:     if ($sec ne '') {
                   6718:         $area .= '/'.$sec;
                   6719:     }
1.994     raeburn  6720:     my $spec = $role.'.'.$area;
                   6721:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6722:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6723:     my %rolehash = ();
1.1172.2.89  raeburn  6724:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6725:         my $rolename = $1;
1.1172.2.84  raeburn  6726:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6727:         my %domdef = &get_domain_defaults($dcdom);
                   6728:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6729:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6730:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6731:             }
                   6732:         }
1.1172.2.84  raeburn  6733:     } else {
                   6734:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6735:     }
1.1172.2.91  raeburn  6736:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6737:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6738:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6739:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6740:         &appenv( {'request.role'        => $spec,
                   6741:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6742:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6743:                  }
                   6744:                );
                   6745:         my $tadv=0;
                   6746:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6747:         &appenv({'request.role.adv'    => $tadv});
                   6748:     }
1.994     raeburn  6749: }
                   6750: 
1.12      www      6751: # --------------------------------------------------------------- get interface
                   6752: 
                   6753: sub get {
1.131     albertel 6754:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6755:    my $items='';
1.800     albertel 6756:    foreach my $item (@$storearr) {
                   6757:        $items.=&escape($item).'&';
1.191     harris41 6758:    }
1.12      www      6759:    $items=~s/\&$//;
1.620     albertel 6760:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6761:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6762:    my $uhome=&homeserver($uname,$udomain);
                   6763: 
1.133     albertel 6764:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6765:    my @pairs=split(/\&/,$rep);
1.273     albertel 6766:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6767:      return @pairs;
                   6768:    }
1.15      www      6769:    my %returnhash=();
1.42      www      6770:    my $i=0;
1.800     albertel 6771:    foreach my $item (@$storearr) {
                   6772:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6773:       $i++;
1.191     harris41 6774:    }
1.15      www      6775:    return %returnhash;
1.27      www      6776: }
                   6777: 
                   6778: # --------------------------------------------------------------- del interface
                   6779: 
                   6780: sub del {
1.133     albertel 6781:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6782:    my $items='';
1.800     albertel 6783:    foreach my $item (@$storearr) {
                   6784:        $items.=&escape($item).'&';
1.191     harris41 6785:    }
1.984     neumanie 6786: 
1.27      www      6787:    $items=~s/\&$//;
1.620     albertel 6788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6789:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6790:    my $uhome=&homeserver($uname,$udomain);
                   6791:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6792: }
                   6793: 
                   6794: # -------------------------------------------------------------- dump interface
                   6795: 
1.1172.2.22  raeburn  6796: sub unserialize {
                   6797:     my ($rep, $escapedkeys) = @_;
                   6798: 
                   6799:     return {} if $rep =~ /^error/;
                   6800: 
                   6801:     my %returnhash=();
                   6802:     foreach my $item (split(/\&/,$rep)) {
                   6803:         my ($key, $value) = split(/=/, $item, 2);
                   6804:         $key = unescape($key) unless $escapedkeys;
                   6805:         next if $key =~ /^error: 2 /;
                   6806:         $returnhash{$key} = &thaw_unescape($value);
                   6807:     }
                   6808:     return \%returnhash;
                   6809: }
                   6810: 
                   6811: # see Lond::dump_with_regexp
                   6812: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6813: sub dump {
1.1172.2.22  raeburn  6814:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6815:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6816:     if (!$uname) { $uname=$env{'user.name'}; }
                   6817:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6818: 
1.1172.2.55  raeburn  6819:     if ($regexp) {
                   6820:         $regexp=&escape($regexp);
                   6821:     } else {
                   6822:         $regexp='.';
                   6823:     }
1.1172.2.22  raeburn  6824:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6825:         # user is hosted on this machine
1.1172.2.55  raeburn  6826:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6827:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6828:         return %{&unserialize($reply, $escapedkeys)};
                   6829:     }
1.1166    raeburn  6830:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6831:     my @pairs=split(/\&/,$rep);
                   6832:     my %returnhash=();
1.1098    foxr     6833:     if (!($rep =~ /^error/ )) {
                   6834: 	foreach my $item (@pairs) {
                   6835: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6836:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6837: 	    next if ($key =~ /^error: 2 /);
                   6838: 	    $returnhash{$key}=&thaw_unescape($value);
                   6839: 	}
1.755     albertel 6840:     }
                   6841:     return %returnhash;
1.407     www      6842: }
                   6843: 
1.1098    foxr     6844: 
1.717     albertel 6845: # --------------------------------------------------------- dumpstore interface
                   6846: 
                   6847: sub dumpstore {
                   6848:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6849:    # same as dump but keys must be escaped. They may contain colon separated
                   6850:    # lists of values that may themself contain colons (e.g. symbs).
                   6851:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6852: }
                   6853: 
1.407     www      6854: # -------------------------------------------------------------- keys interface
                   6855: 
                   6856: sub getkeys {
                   6857:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6858:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6859:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6860:    my $uhome=&homeserver($uname,$udomain);
                   6861:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6862:    my @keyarray=();
1.800     albertel 6863:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6864:       next if ($key =~ /^error: 2 /);
1.800     albertel 6865:       push(@keyarray,&unescape($key));
1.407     www      6866:    }
                   6867:    return @keyarray;
1.318     matthew  6868: }
                   6869: 
1.319     matthew  6870: # --------------------------------------------------------------- currentdump
                   6871: sub currentdump {
1.328     matthew  6872:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6873:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6874:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6875:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6876:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6877:    my $rep;
                   6878: 
                   6879:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6880:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6881:                    $courseid)));
                   6882:    } else {
                   6883:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6884:    }
                   6885: 
1.318     matthew  6886:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6887:    #
1.318     matthew  6888:    my %returnhash=();
1.319     matthew  6889:    #
                   6890:    if ($rep eq "unknown_cmd") { 
                   6891:        # an old lond will not know currentdump
                   6892:        # Do a dump and make it look like a currentdump
1.822     albertel 6893:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6894:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6895:        my %hash = @tmp;
                   6896:        @tmp=();
1.424     matthew  6897:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6898:    } else {
                   6899:        my @pairs=split(/\&/,$rep);
1.800     albertel 6900:        foreach my $pair (@pairs) {
                   6901:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6902:            my ($symb,$param) = split(/:/,$key);
                   6903:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6904:                                                         &thaw_unescape($value);
1.319     matthew  6905:        }
1.191     harris41 6906:    }
1.12      www      6907:    return %returnhash;
1.424     matthew  6908: }
                   6909: 
                   6910: sub convert_dump_to_currentdump{
                   6911:     my %hash = %{shift()};
                   6912:     my %returnhash;
                   6913:     # Code ripped from lond, essentially.  The only difference
                   6914:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6915:     # we might run in to problems with parameter names =~ /^v\./
                   6916:     while (my ($key,$value) = each(%hash)) {
                   6917:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6918: 	$symb  = &unescape($symb);
                   6919: 	$param = &unescape($param);
1.424     matthew  6920:         next if ($v eq 'version' || $symb eq 'keys');
                   6921:         next if (exists($returnhash{$symb}) &&
                   6922:                  exists($returnhash{$symb}->{$param}) &&
                   6923:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6924:         $returnhash{$symb}->{$param}=$value;
                   6925:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6926:     }
                   6927:     #
                   6928:     # Remove all of the keys in the hashes which keep track of
                   6929:     # the version of the parameter.
                   6930:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6931:         # use a foreach because we are going to delete from the hash.
                   6932:         foreach my $key (keys(%$param_hash)) {
                   6933:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6934:         }
                   6935:     }
                   6936:     return \%returnhash;
1.12      www      6937: }
                   6938: 
1.627     albertel 6939: # ------------------------------------------------------ critical inc interface
                   6940: 
                   6941: sub cinc {
                   6942:     return &inc(@_,'critical');
                   6943: }
                   6944: 
1.449     matthew  6945: # --------------------------------------------------------------- inc interface
                   6946: 
                   6947: sub inc {
1.627     albertel 6948:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6949:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6950:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6951:     my $uhome=&homeserver($uname,$udomain);
                   6952:     my $items='';
                   6953:     if (! ref($store)) {
                   6954:         # got a single value, so use that instead
                   6955:         $items = &escape($store).'=&';
                   6956:     } elsif (ref($store) eq 'SCALAR') {
                   6957:         $items = &escape($$store).'=&';        
                   6958:     } elsif (ref($store) eq 'ARRAY') {
                   6959:         $items = join('=&',map {&escape($_);} @{$store});
                   6960:     } elsif (ref($store) eq 'HASH') {
                   6961:         while (my($key,$value) = each(%{$store})) {
                   6962:             $items.= &escape($key).'='.&escape($value).'&';
                   6963:         }
                   6964:     }
                   6965:     $items=~s/\&$//;
1.627     albertel 6966:     if ($critical) {
                   6967: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6968:     } else {
                   6969: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6970:     }
1.449     matthew  6971: }
                   6972: 
1.12      www      6973: # --------------------------------------------------------------- put interface
                   6974: 
                   6975: sub put {
1.134     albertel 6976:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6977:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6978:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6979:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6980:    my $items='';
1.800     albertel 6981:    foreach my $item (keys(%$storehash)) {
                   6982:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6983:    }
1.12      www      6984:    $items=~s/\&$//;
1.134     albertel 6985:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6986: }
                   6987: 
1.631     albertel 6988: # ------------------------------------------------------------ newput interface
                   6989: 
                   6990: sub newput {
                   6991:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6992:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6993:    if (!$uname) { $uname=$env{'user.name'}; }
                   6994:    my $uhome=&homeserver($uname,$udomain);
                   6995:    my $items='';
                   6996:    foreach my $key (keys(%$storehash)) {
                   6997:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6998:    }
                   6999:    $items=~s/\&$//;
                   7000:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7001: }
                   7002: 
                   7003: # ---------------------------------------------------------  putstore interface
                   7004: 
1.524     raeburn  7005: sub putstore {
1.1172.2.59  raeburn  7006:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7007:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7008:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7009:    my $uhome=&homeserver($uname,$udomain);
                   7010:    my $items='';
1.715     albertel 7011:    foreach my $key (keys(%$storehash)) {
                   7012:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7013:    }
1.715     albertel 7014:    $items=~s/\&$//;
1.716     albertel 7015:    my $esc_symb=&escape($symb);
                   7016:    my $esc_v=&escape($version);
1.715     albertel 7017:    my $reply =
1.716     albertel 7018:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7019: 	      $uhome);
1.1172.2.59  raeburn  7020:    if (($tolog) && ($reply eq 'ok')) {
                   7021:        my $namevalue='';
                   7022:        foreach my $key (keys(%{$storehash})) {
                   7023:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7024:        }
                   7025:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7026:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7027:                      '&version='.$esc_v.
                   7028:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7029:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7030:    }
1.715     albertel 7031:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7032:        # gfall back to way things use to be done
1.715     albertel 7033:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7034: 			    $uname);
1.524     raeburn  7035:    }
1.715     albertel 7036:    return $reply;
                   7037: }
                   7038: 
                   7039: sub old_putstore {
1.716     albertel 7040:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7041:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7042:     if (!$uname) { $uname=$env{'user.name'}; }
                   7043:     my $uhome=&homeserver($uname,$udomain);
                   7044:     my %newstorehash;
1.800     albertel 7045:     foreach my $item (keys(%$storehash)) {
                   7046: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7047: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7048:     }
                   7049:     my $items='';
                   7050:     my %allitems = ();
1.800     albertel 7051:     foreach my $item (keys(%newstorehash)) {
                   7052: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7053: 	    my $key = $1.':keys:'.$2;
                   7054: 	    $allitems{$key} .= $3.':';
                   7055: 	}
1.800     albertel 7056: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7057:     }
1.800     albertel 7058:     foreach my $item (keys(%allitems)) {
                   7059: 	$allitems{$item} =~ s/\:$//;
                   7060: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7061:     }
                   7062:     $items=~s/\&$//;
                   7063:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7064: }
                   7065: 
1.47      www      7066: # ------------------------------------------------------ critical put interface
                   7067: 
                   7068: sub cput {
1.134     albertel 7069:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7070:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7071:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7072:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7073:    my $items='';
1.800     albertel 7074:    foreach my $item (keys(%$storehash)) {
                   7075:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7076:    }
1.47      www      7077:    $items=~s/\&$//;
1.134     albertel 7078:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7079: }
                   7080: 
                   7081: # -------------------------------------------------------------- eget interface
                   7082: 
                   7083: sub eget {
1.133     albertel 7084:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7085:    my $items='';
1.800     albertel 7086:    foreach my $item (@$storearr) {
                   7087:        $items.=&escape($item).'&';
1.191     harris41 7088:    }
1.12      www      7089:    $items=~s/\&$//;
1.620     albertel 7090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7091:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7092:    my $uhome=&homeserver($uname,$udomain);
                   7093:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7094:    my @pairs=split(/\&/,$rep);
                   7095:    my %returnhash=();
1.42      www      7096:    my $i=0;
1.800     albertel 7097:    foreach my $item (@$storearr) {
                   7098:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7099:       $i++;
1.191     harris41 7100:    }
1.12      www      7101:    return %returnhash;
                   7102: }
                   7103: 
1.667     albertel 7104: # ------------------------------------------------------------ tmpput interface
                   7105: sub tmpput {
1.802     raeburn  7106:     my ($storehash,$server,$context)=@_;
1.667     albertel 7107:     my $items='';
1.800     albertel 7108:     foreach my $item (keys(%$storehash)) {
                   7109: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7110:     }
                   7111:     $items=~s/\&$//;
1.802     raeburn  7112:     if (defined($context)) {
                   7113:         $items .= ':'.&escape($context);
                   7114:     }
1.667     albertel 7115:     return &reply("tmpput:$items",$server);
                   7116: }
                   7117: 
                   7118: # ------------------------------------------------------------ tmpget interface
                   7119: sub tmpget {
1.688     albertel 7120:     my ($token,$server)=@_;
                   7121:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7122:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7123:     my %returnhash;
1.1172.2.85  raeburn  7124:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7125:         return %returnhash;
                   7126:     }
1.667     albertel 7127:     foreach my $item (split(/\&/,$rep)) {
                   7128: 	my ($key,$value)=split(/=/,$item);
                   7129: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7130:     }
                   7131:     return %returnhash;
                   7132: }
                   7133: 
1.1113    raeburn  7134: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7135: sub tmpdel {
                   7136:     my ($token,$server)=@_;
                   7137:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7138:     return &reply("tmpdel:$token",$server);
                   7139: }
                   7140: 
1.1172.2.13  raeburn  7141: # ------------------------------------------------------------ get_timebased_id
                   7142: 
                   7143: sub get_timebased_id {
                   7144:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7145:         $maxtries) = @_;
                   7146:     my ($newid,$error,$dellock);
                   7147:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7148:         return ('','ok','invalid call to get suffix');
                   7149:     }
                   7150: 
                   7151: # set defaults for any optional args for which values were not supplied
                   7152:     if ($who eq '') {
                   7153:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7154:     }
                   7155:     if (!$locktries) {
                   7156:         $locktries = 3;
                   7157:     }
                   7158:     if (!$maxtries) {
                   7159:         $maxtries = 10;
                   7160:     }
                   7161: 
                   7162:     if (($cdom eq '') || ($cnum eq '')) {
                   7163:         if ($env{'request.course.id'}) {
                   7164:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7165:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7166:         }
                   7167:         if (($cdom eq '') || ($cnum eq '')) {
                   7168:             return ('','ok','call to get suffix not in course context');
                   7169:         }
                   7170:     }
                   7171: 
                   7172: # construct locking item
                   7173:     my $lockhash = {
                   7174:                       $prefix."\0".'locked_'.$keyid => $who,
                   7175:                    };
                   7176:     my $tries = 0;
                   7177: 
                   7178: # attempt to get lock on nohist_$namespace file
                   7179:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7180:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7181:         $tries ++;
                   7182:         sleep 1;
                   7183:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7184:     }
                   7185: 
                   7186: # attempt to get unique identifier, based on current timestamp
                   7187:     if ($gotlock eq 'ok') {
                   7188:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7189:         my $id = time;
                   7190:         $newid = $id;
1.1172.2.56  raeburn  7191:         if ($idtype eq 'addcode') {
                   7192:             $newid .= &sixnum_code();
                   7193:         }
1.1172.2.13  raeburn  7194:         my $idtries = 0;
                   7195:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7196:             if ($idtype eq 'concat') {
                   7197:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7198:             } elsif ($idtype eq 'addcode') {
                   7199:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7200:             } else {
                   7201:                 $newid ++;
                   7202:             }
                   7203:             $idtries ++;
                   7204:         }
                   7205:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7206:             my %new_item =  (
                   7207:                               $prefix."\0".$newid => $who,
                   7208:                             );
                   7209:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7210:                                                  $cdom,$cnum);
                   7211:             if ($putresult ne 'ok') {
                   7212:                 undef($newid);
                   7213:                 $error = 'error saving new item: '.$putresult;
                   7214:             }
                   7215:         } else {
1.1172.2.56  raeburn  7216:              undef($newid);
1.1172.2.13  raeburn  7217:              $error = ('error: no unique suffix available for the new item ');
                   7218:         }
                   7219: #  remove lock
                   7220:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7221:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7222:     } else {
                   7223:         $error = "error: could not obtain lockfile\n";
                   7224:         $dellock = 'ok';
1.1172.2.58  raeburn  7225:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7226:             $dellock = 'nolock';
                   7227:         }
1.1172.2.13  raeburn  7228:     }
                   7229:     return ($newid,$dellock,$error);
                   7230: }
                   7231: 
1.1172.2.56  raeburn  7232: sub sixnum_code {
                   7233:     my $code;
                   7234:     for (0..6) {
                   7235:         $code .= int( rand(9) );
                   7236:     }
                   7237:     return $code;
                   7238: }
                   7239: 
1.765     albertel 7240: # -------------------------------------------------- portfolio access checking
                   7241: 
                   7242: sub portfolio_access {
1.1172.2.77  raeburn  7243:     my ($requrl,$clientip) = @_;
1.765     albertel 7244:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7245:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7246:     if ($result) {
                   7247:         my %setters;
                   7248:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7249:             my ($startblock,$endblock) =
                   7250:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7251:             if ($startblock && $endblock) {
                   7252:                 return 'B';
                   7253:             }
                   7254:         } else {
                   7255:             my ($startblock,$endblock) =
                   7256:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7257:             if ($startblock && $endblock) {
                   7258:                 return 'B';
                   7259:             }
                   7260:         }
                   7261:     }
1.765     albertel 7262:     if ($result eq 'ok') {
1.766     albertel 7263:        return 'F';
1.765     albertel 7264:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7265:        return 'A';
1.765     albertel 7266:     }
1.766     albertel 7267:     return '';
1.765     albertel 7268: }
                   7269: 
                   7270: sub get_portfolio_access {
1.1172.2.77  raeburn  7271:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7272: 
                   7273:     if (!ref($access_hash)) {
                   7274: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7275: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7276: 						   $file_name);
                   7277: 	$access_hash = $access_controls{$file_name};
                   7278:     }
                   7279: 
1.1172.2.77  raeburn  7280:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7281:     my $now = time;
                   7282:     if (ref($access_hash) eq 'HASH') {
                   7283:         foreach my $key (keys(%{$access_hash})) {
                   7284:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7285:             if ($start > $now) {
                   7286:                 next;
                   7287:             }
                   7288:             if ($end && $end<$now) {
                   7289:                 next;
                   7290:             }
                   7291:             if ($scope eq 'public') {
                   7292:                 $public = $key;
                   7293:                 last;
                   7294:             } elsif ($scope eq 'guest') {
                   7295:                 $guest = $key;
                   7296:             } elsif ($scope eq 'domains') {
                   7297:                 push(@domains,$key);
                   7298:             } elsif ($scope eq 'users') {
                   7299:                 push(@users,$key);
                   7300:             } elsif ($scope eq 'course') {
                   7301:                 push(@courses,$key);
                   7302:             } elsif ($scope eq 'group') {
                   7303:                 push(@groups,$key);
1.1172.2.77  raeburn  7304:             } elsif ($scope eq 'ip') {
                   7305:                 push(@ips,$key);
1.765     albertel 7306:             }
                   7307:         }
                   7308:         if ($public) {
                   7309:             return 'ok';
1.1172.2.77  raeburn  7310:         } elsif (@ips > 0) {
                   7311:             my $allowed;
                   7312:             foreach my $ipkey (@ips) {
                   7313:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7314:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7315:                         $allowed = 1;
                   7316:                         last;
                   7317:                     }
                   7318:                 }
                   7319:             }
                   7320:             if ($allowed) {
                   7321:                 return 'ok';
                   7322:             }
1.765     albertel 7323:         }
                   7324:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7325:             if ($guest) {
                   7326:                 return $guest;
                   7327:             }
                   7328:         } else {
                   7329:             if (@domains > 0) {
                   7330:                 foreach my $domkey (@domains) {
                   7331:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7332:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7333:                             return 'ok';
                   7334:                         }
                   7335:                     }
                   7336:                 }
                   7337:             }
                   7338:             if (@users > 0) {
                   7339:                 foreach my $userkey (@users) {
1.865     raeburn  7340:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7341:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7342:                             if (ref($item) eq 'HASH') {
                   7343:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7344:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7345:                                     return 'ok';
                   7346:                                 }
                   7347:                             }
                   7348:                         }
                   7349:                     } 
1.765     albertel 7350:                 }
                   7351:             }
                   7352:             my %roleshash;
                   7353:             my @courses_and_groups = @courses;
                   7354:             push(@courses_and_groups,@groups); 
                   7355:             if (@courses_and_groups > 0) {
                   7356:                 my (%allgroups,%allroles); 
                   7357:                 my ($start,$end,$role,$sec,$group);
                   7358:                 foreach my $envkey (%env) {
1.1060    raeburn  7359:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7360:                         my $cid = $2.'_'.$3; 
                   7361:                         if ($1 eq 'gr') {
                   7362:                             $group = $4;
                   7363:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7364:                         } else {
                   7365:                             if ($4 eq '') {
                   7366:                                 $sec = 'none';
                   7367:                             } else {
                   7368:                                 $sec = $4;
                   7369:                             }
                   7370:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7371:                         }
1.811     albertel 7372:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7373:                         my $cid = $2.'_'.$3;
                   7374:                         if ($4 eq '') {
                   7375:                             $sec = 'none';
                   7376:                         } else {
                   7377:                             $sec = $4;
                   7378:                         }
                   7379:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7380:                     }
                   7381:                 }
                   7382:                 if (keys(%allroles) == 0) {
                   7383:                     return;
                   7384:                 }
                   7385:                 foreach my $key (@courses_and_groups) {
                   7386:                     my %content = %{$$access_hash{$key}};
                   7387:                     my $cnum = $content{'number'};
                   7388:                     my $cdom = $content{'domain'};
                   7389:                     my $cid = $cdom.'_'.$cnum;
                   7390:                     if (!exists($allroles{$cid})) {
                   7391:                         next;
                   7392:                     }    
                   7393:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7394:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7395:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7396:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7397:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7398:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7399:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7400:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7401:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7402:                                         if (grep/^all$/,@sections) {
                   7403:                                             return 'ok';
                   7404:                                         } else {
                   7405:                                             if (grep/^$sec$/,@sections) {
                   7406:                                                 return 'ok';
                   7407:                                             }
                   7408:                                         }
                   7409:                                     }
                   7410:                                 }
                   7411:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7412:                                     if (grep/^none$/,@groups) {
                   7413:                                         return 'ok';
                   7414:                                     }
                   7415:                                 } else {
                   7416:                                     if (grep/^all$/,@groups) {
                   7417:                                         return 'ok';
                   7418:                                     } 
                   7419:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7420:                                         if (grep/^$group$/,@groups) {
                   7421:                                             return 'ok';
                   7422:                                         }
                   7423:                                     }
                   7424:                                 } 
                   7425:                             }
                   7426:                         }
                   7427:                     }
                   7428:                 }
                   7429:             }
                   7430:             if ($guest) {
                   7431:                 return $guest;
                   7432:             }
                   7433:         }
                   7434:     }
                   7435:     return;
                   7436: }
                   7437: 
                   7438: sub course_group_datechecker {
                   7439:     my ($dates,$now,$status) = @_;
                   7440:     my ($start,$end) = split(/\./,$dates);
                   7441:     if (!$start && !$end) {
                   7442:         return 'ok';
                   7443:     }
                   7444:     if (grep/^active$/,@{$status}) {
                   7445:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7446:             return 'ok';
                   7447:         }
                   7448:     }
                   7449:     if (grep/^previous$/,@{$status}) {
                   7450:         if ($end > $now ) {
                   7451:             return 'ok';
                   7452:         }
                   7453:     }
                   7454:     if (grep/^future$/,@{$status}) {
                   7455:         if ($start > $now) {
                   7456:             return 'ok';
                   7457:         }
                   7458:     }
                   7459:     return; 
                   7460: }
                   7461: 
                   7462: sub parse_portfolio_url {
                   7463:     my ($url) = @_;
                   7464: 
                   7465:     my ($type,$udom,$unum,$group,$file_name);
                   7466:     
1.823     albertel 7467:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7468: 	$type = 1;
                   7469:         $udom = $1;
                   7470:         $unum = $2;
                   7471:         $file_name = $3;
1.823     albertel 7472:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7473: 	$type = 2;
                   7474:         $udom = $1;
                   7475:         $unum = $2;
                   7476:         $group = $3;
                   7477:         $file_name = $3.'/'.$4;
                   7478:     }
                   7479:     if (wantarray) {
                   7480: 	return ($type,$udom,$unum,$file_name,$group);
                   7481:     }
                   7482:     return $type;
                   7483: }
                   7484: 
                   7485: sub is_portfolio_url {
                   7486:     my ($url) = @_;
                   7487:     return scalar(&parse_portfolio_url($url));
                   7488: }
                   7489: 
1.798     raeburn  7490: sub is_portfolio_file {
                   7491:     my ($file) = @_;
1.820     raeburn  7492:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7493:         return 1;
                   7494:     }
                   7495:     return;
                   7496: }
                   7497: 
1.976     raeburn  7498: sub usertools_access {
1.1084    raeburn  7499:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7500:     my ($access,%tools);
                   7501:     if ($context eq '') {
                   7502:         $context = 'tools';
                   7503:     }
                   7504:     if ($context eq 'requestcourses') {
                   7505:         %tools = (
                   7506:                       official   => 1,
                   7507:                       unofficial => 1,
1.1006    raeburn  7508:                       community  => 1,
1.1172.2.37  raeburn  7509:                       textbook   => 1,
1.985     raeburn  7510:                  );
1.1172.2.9  raeburn  7511:     } elsif ($context eq 'requestauthor') {
                   7512:         %tools = (
                   7513:                       requestauthor => 1,
                   7514:                  );
1.985     raeburn  7515:     } else {
                   7516:         %tools = (
                   7517:                       aboutme   => 1,
                   7518:                       blog      => 1,
1.1172.2.6  raeburn  7519:                       webdav    => 1,
1.985     raeburn  7520:                       portfolio => 1,
                   7521:                  );
                   7522:     }
1.976     raeburn  7523:     return if (!defined($tools{$tool}));
                   7524: 
1.1172.2.35  raeburn  7525:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7526:         $udom = $env{'user.domain'};
                   7527:         $uname = $env{'user.name'};
                   7528:     }
                   7529: 
1.978     raeburn  7530:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7531:         if ($action ne 'reload') {
1.985     raeburn  7532:             if ($context eq 'requestcourses') {
                   7533:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7534:             } elsif ($context eq 'requestauthor') {
                   7535:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7536:             } else {
                   7537:                 return $env{'environment.availabletools.'.$tool};
                   7538:             }
                   7539:         }
1.976     raeburn  7540:     }
                   7541: 
1.1172.2.9  raeburn  7542:     my ($toolstatus,$inststatus,$envkey);
                   7543:     if ($context eq 'requestauthor') {
                   7544:         $envkey = $context;
                   7545:     } else {
                   7546:         $envkey = $context.'.'.$tool;
                   7547:     }
1.976     raeburn  7548: 
1.985     raeburn  7549:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7550:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7551:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7552:         $inststatus = $env{'environment.inststatus'};
                   7553:     } else {
1.1084    raeburn  7554:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7555:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7556:             $inststatus = $userenvref->{'inststatus'};
                   7557:         } else {
1.1172.2.9  raeburn  7558:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7559:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7560:             $inststatus = $userenv{'inststatus'};
                   7561:         }
1.976     raeburn  7562:     }
                   7563: 
                   7564:     if ($toolstatus ne '') {
                   7565:         if ($toolstatus) {
                   7566:             $access = 1;
                   7567:         } else {
                   7568:             $access = 0;
                   7569:         }
                   7570:         return $access;
                   7571:     }
                   7572: 
1.1084    raeburn  7573:     my ($is_adv,%domdef);
                   7574:     if (ref($is_advref) eq 'HASH') {
                   7575:         $is_adv = $is_advref->{'is_adv'};
                   7576:     } else {
                   7577:         $is_adv = &is_advanced_user($udom,$uname);
                   7578:     }
                   7579:     if (ref($domdefref) eq 'HASH') {
                   7580:         %domdef = %{$domdefref};
                   7581:     } else {
                   7582:         %domdef = &get_domain_defaults($udom);
                   7583:     }
1.976     raeburn  7584:     if (ref($domdef{$tool}) eq 'HASH') {
                   7585:         if ($is_adv) {
                   7586:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7587:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7588:                     $access = 1;
                   7589:                 } else {
                   7590:                     $access = 0;
                   7591:                 }
                   7592:                 return $access;
                   7593:             }
                   7594:         }
                   7595:         if ($inststatus ne '') {
                   7596:             my ($hasaccess,$hasnoaccess);
                   7597:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7598:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7599:                     if ($domdef{$tool}{$affiliation}) {
                   7600:                         $hasaccess = 1;
                   7601:                     } else {
                   7602:                         $hasnoaccess = 1;
                   7603:                     }
                   7604:                 }
                   7605:             }
                   7606:             if ($hasaccess || $hasnoaccess) {
                   7607:                 if ($hasaccess) {
                   7608:                     $access = 1;
                   7609:                 } elsif ($hasnoaccess) {
                   7610:                     $access = 0; 
                   7611:                 }
                   7612:                 return $access;
                   7613:             }
                   7614:         } else {
                   7615:             if ($domdef{$tool}{'default'} ne '') {
                   7616:                 if ($domdef{$tool}{'default'}) {
                   7617:                     $access = 1;
                   7618:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7619:                     $access = 0;
                   7620:                 }
                   7621:                 return $access;
                   7622:             }
                   7623:         }
                   7624:     } else {
1.1172.2.6  raeburn  7625:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7626:             $access = 1;
                   7627:         } else {
                   7628:             $access = 0;
                   7629:         }
1.976     raeburn  7630:         return $access;
                   7631:     }
                   7632: }
                   7633: 
1.1050    raeburn  7634: sub is_course_owner {
                   7635:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7636:     if (($udom eq '') || ($uname eq '')) {
                   7637:         $udom = $env{'user.domain'};
                   7638:         $uname = $env{'user.name'};
                   7639:     }
                   7640:     unless (($udom eq '') || ($uname eq '')) {
                   7641:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7642:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7643:                 return 1;
                   7644:             } else {
                   7645:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7646:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7647:                     return 1;
                   7648:                 }
                   7649:             }
                   7650:         }
                   7651:     }
                   7652:     return;
                   7653: }
                   7654: 
1.976     raeburn  7655: sub is_advanced_user {
                   7656:     my ($udom,$uname) = @_;
1.1085    raeburn  7657:     if ($udom ne '' && $uname ne '') {
                   7658:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7659:             if (wantarray) {
                   7660:                 return ($env{'user.adv'},$env{'user.author'});
                   7661:             } else {
                   7662:                 return $env{'user.adv'};
                   7663:             }
1.1085    raeburn  7664:         }
                   7665:     }
1.976     raeburn  7666:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7667:     my %allroles;
1.1128    raeburn  7668:     my ($is_adv,$is_author);
1.976     raeburn  7669:     foreach my $role (keys(%roleshash)) {
                   7670:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7671:         my $area = '/'.$tdomain.'/'.$trest;
                   7672:         if ($sec ne '') {
                   7673:             $area .= '/'.$sec;
                   7674:         }
                   7675:         if (($area ne '') && ($trole ne '')) {
                   7676:             my $spec=$trole.'.'.$area;
                   7677:             if ($trole =~ /^cr\//) {
                   7678:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7679:             } elsif ($trole ne 'gr') {
                   7680:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7681:             }
1.1128    raeburn  7682:             if ($trole eq 'au') {
                   7683:                 $is_author = 1;
                   7684:             }
1.976     raeburn  7685:         }
                   7686:     }
                   7687:     foreach my $role (keys(%allroles)) {
                   7688:         last if ($is_adv);
                   7689:         foreach my $item (split(/:/,$allroles{$role})) {
                   7690:             if ($item ne '') {
                   7691:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7692:                 if ($privilege eq 'adv') {
                   7693:                     $is_adv = 1;
                   7694:                     last;
                   7695:                 }
                   7696:             }
                   7697:         }
                   7698:     }
1.1128    raeburn  7699:     if (wantarray) {
                   7700:         return ($is_adv,$is_author);
                   7701:     }
1.976     raeburn  7702:     return $is_adv;
                   7703: }
1.798     raeburn  7704: 
1.1035    raeburn  7705: sub check_can_request {
1.1036    raeburn  7706:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7707:     my $canreq = 0;
                   7708:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7709:     my @options = ('approval','validate','autolimit');
                   7710:     my $optregex = join('|',@options);
                   7711:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7712:         foreach my $type (@{$types}) {
                   7713:             if (&usertools_access($env{'user.name'},
                   7714:                                   $env{'user.domain'},
                   7715:                                   $type,undef,'requestcourses')) {
                   7716:                 $canreq ++;
1.1036    raeburn  7717:                 if (ref($request_domains) eq 'HASH') {
                   7718:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7719:                 }
1.1035    raeburn  7720:                 if ($dom eq $env{'user.domain'}) {
                   7721:                     $can_request->{$type} = 1;
                   7722:                 }
                   7723:             }
                   7724:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7725:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7726:                 if (@curr > 0) {
1.1036    raeburn  7727:                     foreach my $item (@curr) {
                   7728:                         if (ref($request_domains) eq 'HASH') {
                   7729:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7730:                             if ($otherdom ne '') {
                   7731:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7732:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7733:                                         push(@{$request_domains->{$type}},$otherdom);
                   7734:                                     }
                   7735:                                 } else {
                   7736:                                     push(@{$request_domains->{$type}},$otherdom);
                   7737:                                 }
                   7738:                             }
                   7739:                         }
                   7740:                     }
                   7741:                     unless($dom eq $env{'user.domain'}) {
                   7742:                         $canreq ++;
1.1035    raeburn  7743:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7744:                             $can_request->{$type} = 1;
                   7745:                         }
                   7746:                     }
                   7747:                 }
                   7748:             }
                   7749:         }
                   7750:     }
                   7751:     return $canreq;
                   7752: }
                   7753: 
1.341     www      7754: # ---------------------------------------------- Custom access rule evaluation
                   7755: 
                   7756: sub customaccess {
                   7757:     my ($priv,$uri)=@_;
1.807     albertel 7758:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7759:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7760:     $udom = &LONCAPA::clean_domain($udom);
                   7761:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7762:     my $access=0;
1.800     albertel 7763:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7764: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7765: 	if ($type eq 'user') {
                   7766: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7767: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7768: 		if ($tdom) {
                   7769: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7770: 		}
1.896     albertel 7771: 		if ($tuname) {
                   7772: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7773: 		}
                   7774: 		$access=($effect eq 'allow');
                   7775: 		last;
                   7776: 	    }
                   7777: 	} else {
                   7778: 	    if ($role) {
                   7779: 		if ($role ne $urole) { next; }
                   7780: 	    }
                   7781: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7782: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7783: 		if ($tdom) {
                   7784: 		    if ($tdom ne $udom) { next; }
                   7785: 		}
                   7786: 		if ($tcrs) {
                   7787: 		    if ($tcrs ne $ucrs) { next; }
                   7788: 		}
                   7789: 		if ($tsec) {
                   7790: 		    if ($tsec ne $usec) { next; }
                   7791: 		}
                   7792: 		$access=($effect eq 'allow');
                   7793: 		last;
                   7794: 	    }
                   7795: 	    if ($realm eq '' && $role eq '') {
                   7796: 		$access=($effect eq 'allow');
                   7797: 	    }
1.402     bowersj2 7798: 	}
1.341     www      7799:     }
                   7800:     return $access;
                   7801: }
                   7802: 
1.103     harris41 7803: # ------------------------------------------------- Check for a user privilege
1.12      www      7804: 
                   7805: sub allowed {
1.1172.2.126  raeburn  7806:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7807:     my $ver_orguri=$uri;
1.439     www      7808:     $uri=&deversion($uri);
1.152     www      7809:     my $orguri=$uri;
1.52      www      7810:     $uri=&declutter($uri);
1.809     raeburn  7811: 
1.810     raeburn  7812:     if ($priv eq 'evb') {
                   7813: # Evade communication block restrictions for specified role in a course
                   7814:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7815:             return $1;
                   7816:         } else {
                   7817:             return;
                   7818:         }
                   7819:     }
                   7820: 
1.620     albertel 7821:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7822: # Free bre access to adm and meta resources
1.775     albertel 7823:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7824: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7825: 	&& ($priv eq 'bre')) {
1.14      www      7826: 	return 'F';
1.159     www      7827:     }
                   7828: 
1.545     banghart 7829: # Free bre access to user's own portfolio contents
1.714     raeburn  7830:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7831:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7832: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7833:         my %setters;
                   7834:         my ($startblock,$endblock) = 
                   7835:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7836:         if ($startblock && $endblock) {
                   7837:             return 'B';
                   7838:         } else {
                   7839:             return 'F';
                   7840:         }
1.545     banghart 7841:     }
                   7842: 
1.762     raeburn  7843: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7844:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7845:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7846:         if (exists($env{'request.course.id'})) {
                   7847:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7848:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7849:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7850:                 my $courseprivid=$env{'request.course.id'};
                   7851:                 $courseprivid=~s/\_/\//;
                   7852:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7853:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7854:                     return $1; 
1.762     raeburn  7855:                 } else {
                   7856:                     if ($env{'request.course.sec'}) {
                   7857:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7858:                     }
                   7859:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7860:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7861:                         return $2;
                   7862:                     }
1.714     raeburn  7863:                 }
                   7864:             }
                   7865:         }
                   7866:     }
                   7867: 
1.159     www      7868: # Free bre to public access
                   7869: 
                   7870:     if ($priv eq 'bre') {
1.238     www      7871:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7872: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7873:            return 'F'; 
                   7874:         }
1.238     www      7875:         if ($copyright eq 'priv') {
                   7876:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7877: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7878: 		return '';
                   7879:             }
                   7880:         }
                   7881:         if ($copyright eq 'domain') {
                   7882:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7883: 	    unless (($env{'user.domain'} eq $1) ||
                   7884:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7885: 		return '';
                   7886:             }
1.262     matthew  7887:         }
1.620     albertel 7888:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7889:             # Library role, so allow browsing of resources in this domain.
                   7890:             return 'F';
1.238     www      7891:         }
1.341     www      7892:         if ($copyright eq 'custom') {
                   7893: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7894:         }
1.14      www      7895:     }
1.264     matthew  7896:     # Domain coordinator is trying to create a course
1.620     albertel 7897:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7898:         # uri is the requested domain in this case.
                   7899:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7900:         # a role of dc for the domain in question.
1.620     albertel 7901:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7902:     }
1.29      www      7903: 
1.52      www      7904:     my $thisallowed='';
                   7905:     my $statecond=0;
                   7906:     my $courseprivid='';
                   7907: 
1.1039    raeburn  7908:     my $ownaccess;
1.1043    raeburn  7909:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7910:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7911:         if ($uri eq '') {
                   7912:             $ownaccess = 1;
                   7913:         } else {
                   7914:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7915:                 my $udom = $env{'user.domain'};
                   7916:                 my $uname = $env{'user.name'};
                   7917:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7918:                     $ownaccess = 1;
1.1040    raeburn  7919:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7920:                     unless ($uri =~ m{\.\./}) {
                   7921:                         $ownaccess = 1;
                   7922:                     }
                   7923:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7924:                     my $now = time;
                   7925:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7926:                         my $adom = $1;
                   7927:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7928:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7929:                                 my ($start,$end) = split('.',$env{$key});
                   7930:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7931:                                     $ownaccess = 1;
                   7932:                                     last;
                   7933:                                 }
                   7934:                             }
                   7935:                         }
                   7936:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7937:                         my $adom = $1;
                   7938:                         my $aname = $2;
1.1042    raeburn  7939:                         foreach my $role ('ca','aa') { 
                   7940:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7941:                                 my ($start,$end) =
                   7942:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7943:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7944:                                     $ownaccess = 1;
                   7945:                                     last;
                   7946:                                 }
1.1039    raeburn  7947:                             }
                   7948:                         }
                   7949:                     }
                   7950:                 }
                   7951:             }
                   7952:         }
                   7953:     }
                   7954: 
1.52      www      7955: # Course
                   7956: 
1.620     albertel 7957:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7958:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7959:             $thisallowed.=$1;
                   7960:         }
1.52      www      7961:     }
1.29      www      7962: 
1.52      www      7963: # Domain
                   7964: 
1.620     albertel 7965:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7966:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7967:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7968:             $thisallowed.=$1;
                   7969:         }
1.12      www      7970:     }
1.52      www      7971: 
1.1141    raeburn  7972: # User who is not author or co-author might still be able to edit
                   7973: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7974:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7975:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7976:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7977:             $thisallowed.=$1;
                   7978:         }
                   7979:     }
                   7980: 
1.52      www      7981: # Course: uri itself is a course
1.66      www      7982:     my $courseuri=$uri;
                   7983:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7984:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7985: 
1.620     albertel 7986:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7987:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7988:         if ($priv eq 'mip') {
                   7989:             my $rem = $1;
                   7990:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7991:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7992:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7993:                 if ($cdom ne '') {
                   7994:                     my %passwdconf = &get_passwdconf($cdom);
                   7995:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7996:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7997:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7998:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7999:                                 unless (@inststatuses) {
                   8000:                                     @inststatuses = ('default');
                   8001:                                 }
                   8002:                                 foreach my $status (@inststatuses) {
                   8003:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8004:                                         $thisallowed.=$rem;
                   8005:                                     }
                   8006:                                 }
                   8007:                             }
                   8008:                         }
                   8009:                     }
                   8010:                 }
                   8011:             }
                   8012:         } else {
                   8013:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8014:                 $thisallowed.=$1;
                   8015:             }
1.1039    raeburn  8016:         }
1.12      www      8017:     }
1.29      www      8018: 
1.665     albertel 8019: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8020: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8021:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8022: 	$thisallowed='';
1.671     raeburn  8023:         my ($match)=&is_on_map($uri);
                   8024:         if ($match) {
                   8025:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8026:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8027:                 my $value = $1;
                   8028:                 if ($noblockcheck) {
                   8029:                     $thisallowed.=$value;
1.1162    raeburn  8030:                 } else {
1.1172.2.126  raeburn  8031:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8032:                     if (@blockers > 0) {
                   8033:                         $thisallowed = 'B';
                   8034:                     } else {
                   8035:                         $thisallowed.=$value;
                   8036:                     }
1.1162    raeburn  8037:                 }
1.671     raeburn  8038:             }
                   8039:         } else {
1.705     albertel 8040:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8041:             if ($refuri) {
                   8042:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8043:                     $thisallowed='F';
1.671     raeburn  8044:                 } else {
                   8045:                     $refuri=&declutter($refuri);
                   8046:                     my ($match) = &is_on_map($refuri);
                   8047:                     if ($match) {
1.1172.2.65  raeburn  8048:                         if ($noblockcheck) {
1.1162    raeburn  8049:                             $thisallowed='F';
1.1172.2.65  raeburn  8050:                         } else {
1.1172.2.127  raeburn  8051:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8052:                             if (@blockers > 0) {
                   8053:                                 $thisallowed = 'B';
                   8054:                             } else {
                   8055:                                 $thisallowed='F';
                   8056:                             }
1.1162    raeburn  8057:                         }
1.671     raeburn  8058:                     }
1.669     raeburn  8059:                 }
1.671     raeburn  8060:             }
                   8061:         }
1.314     www      8062:     }
1.492     albertel 8063: 
1.766     albertel 8064:     if ($priv eq 'bre'
                   8065: 	&& $thisallowed ne 'F' 
                   8066: 	&& $thisallowed ne '2'
                   8067: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8068: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8069:     }
                   8070:     
1.52      www      8071: # Full access at system, domain or course-wide level? Exit.
1.29      www      8072:     if ($thisallowed=~/F/) {
                   8073: 	return 'F';
                   8074:     }
                   8075: 
1.52      www      8076: # If this is generating or modifying users, exit with special codes
1.29      www      8077: 
1.643     www      8078:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8079: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8080: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8081: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8082: 	    unless ($auname) { return $thisallowed; }
                   8083: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8084: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8085: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8086: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8087: 	}
1.52      www      8088: 	return $thisallowed;
                   8089:     }
                   8090: #
1.103     harris41 8091: # Gathered so far: system, domain and course wide privileges
1.52      www      8092: #
                   8093: # Course: See if uri or referer is an individual resource that is part of 
                   8094: # the course
                   8095: 
1.620     albertel 8096:     if ($env{'request.course.id'}) {
1.232     www      8097: 
1.1172.2.115  raeburn  8098: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8099: 
                   8100:         if ($priv eq 'mip') {
                   8101:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8102:                 return $thisallowed;
                   8103:             } else {
                   8104:                 return '';
                   8105:             }
                   8106:         }
                   8107: 
1.620     albertel 8108:        $courseprivid=$env{'request.course.id'};
                   8109:        if ($env{'request.course.sec'}) {
                   8110:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8111:        }
                   8112:        $courseprivid=~s/\_/\//;
                   8113:        my $checkreferer=1;
1.232     www      8114:        my ($match,$cond)=&is_on_map($uri);
                   8115:        if ($match) {
                   8116:            $statecond=$cond;
1.620     albertel 8117:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8118:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8119:                my $value = $1;
                   8120:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8121:                    if ($noblockcheck) {
1.1162    raeburn  8122:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8123:                    } else {
1.1172.2.126  raeburn  8124:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8125:                        if (@blockers > 0) {
                   8126:                            $thisallowed = 'B';
                   8127:                        } else {
                   8128:                            $thisallowed.=$value;
                   8129:                        }
1.1162    raeburn  8130:                    }
                   8131:                } else {
                   8132:                    $thisallowed.=$value;
                   8133:                }
1.52      www      8134:                $checkreferer=0;
                   8135:            }
1.29      www      8136:        }
1.1172.2.126  raeburn  8137: 
1.148     www      8138:        if ($checkreferer) {
1.620     albertel 8139: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8140:             unless ($refuri) {
1.800     albertel 8141:                 foreach my $key (keys(%env)) {
                   8142: 		    if ($key=~/^httpref\..*\*/) {
                   8143: 			my $pattern=$key;
1.156     www      8144:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8145:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8146:                         $pattern=~s/\//\\\//g;
1.152     www      8147:                         if ($orguri=~/$pattern/) {
1.800     albertel 8148: 			    $refuri=$env{$key};
1.148     www      8149:                         }
                   8150:                     }
1.191     harris41 8151:                 }
1.148     www      8152:             }
1.232     www      8153: 
1.148     www      8154:          if ($refuri) { 
1.152     www      8155: 	  $refuri=&declutter($refuri);
1.232     www      8156:           my ($match,$cond)=&is_on_map($refuri);
                   8157:             if ($match) {
                   8158:               my $refstatecond=$cond;
1.620     albertel 8159:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8160:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8161:                   my $value = $1;
                   8162:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8163:                       if ($noblockcheck) {
1.1162    raeburn  8164:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8165:                       } else {
1.1172.2.127  raeburn  8166:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8167:                           if (@blockers > 0) {
                   8168:                               $thisallowed = 'B';
                   8169:                           } else {
                   8170:                               $thisallowed.=$value;
                   8171:                           }
1.1162    raeburn  8172:                       }
                   8173:                   } else {
                   8174:                       $thisallowed.=$value;
                   8175:                   }
1.53      www      8176:                   $uri=$refuri;
                   8177:                   $statecond=$refstatecond;
1.52      www      8178:               }
                   8179:           }
1.148     www      8180:         }
1.29      www      8181:        }
1.52      www      8182:    }
1.29      www      8183: 
1.52      www      8184: #
1.103     harris41 8185: # Gathered now: all privileges that could apply, and condition number
1.52      www      8186: # 
                   8187: #
                   8188: # Full or no access?
                   8189: #
1.29      www      8190: 
1.52      www      8191:     if ($thisallowed=~/F/) {
                   8192: 	return 'F';
                   8193:     }
1.29      www      8194: 
1.52      www      8195:     unless ($thisallowed) {
                   8196:         return '';
                   8197:     }
1.29      www      8198: 
1.52      www      8199: # Restrictions exist, deal with them
                   8200: #
                   8201: #   C:according to course preferences
                   8202: #   R:according to resource settings
                   8203: #   L:unless locked
                   8204: #   X:according to user session state
                   8205: #
                   8206: 
                   8207: # Possibly locked functionality, check all courses
1.54      www      8208: # Locks might take effect only after 10 minutes cache expiration for other
                   8209: # courses, and 2 minutes for current course
1.52      www      8210: 
                   8211:     my $envkey;
                   8212:     if ($thisallowed=~/L/) {
1.1000    raeburn  8213:         foreach $envkey (keys(%env)) {
1.54      www      8214:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8215:                my $courseid=$2;
                   8216:                my $roleid=$1.'.'.$2;
1.92      www      8217:                $courseid=~s/^\///;
1.54      www      8218:                my $expiretime=600;
1.620     albertel 8219:                if ($env{'request.role'} eq $roleid) {
1.54      www      8220: 		  $expiretime=120;
                   8221:                }
                   8222: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8223:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8224:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8225: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8226:                }
1.620     albertel 8227:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8228:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8229: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8230:                        &log($env{'user.domain'},$env{'user.name'},
                   8231:                             $env{'user.home'},
1.57      www      8232:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8233:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8234:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8235: 		       return '';
                   8236:                    }
                   8237:                }
1.620     albertel 8238:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8239:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8240: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8241:                        &log($env{'user.domain'},$env{'user.name'},
                   8242:                             $env{'user.home'},
1.57      www      8243:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8244:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8245:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8246: 		       return '';
                   8247:                    }
                   8248:                }
                   8249: 	   }
1.29      www      8250:        }
1.52      www      8251:     }
1.1172.2.126  raeburn  8252: 
1.52      www      8253: #
                   8254: # Rest of the restrictions depend on selected course
                   8255: #
                   8256: 
1.620     albertel 8257:     unless ($env{'request.course.id'}) {
1.766     albertel 8258: 	if ($thisallowed eq 'A') {
                   8259: 	    return 'A';
1.814     raeburn  8260:         } elsif ($thisallowed eq 'B') {
                   8261:             return 'B';
1.766     albertel 8262: 	} else {
                   8263: 	    return '1';
                   8264: 	}
1.52      www      8265:     }
1.29      www      8266: 
1.52      www      8267: #
                   8268: # Now user is definitely in a course
                   8269: #
1.53      www      8270: 
                   8271: 
                   8272: # Course preferences
                   8273: 
                   8274:    if ($thisallowed=~/C/) {
1.620     albertel 8275:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8276:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8277:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8278: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8279: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8280: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8281: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8282: 			$env{'request.course.id'});
                   8283: 	   }
1.237     www      8284:            return '';
                   8285:        }
                   8286: 
1.620     albertel 8287:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8288: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8289: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8290: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8291: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8292: 			$env{'request.course.id'});
                   8293: 	   }
1.54      www      8294:            return '';
                   8295:        }
1.53      www      8296:    }
                   8297: 
                   8298: # Resource preferences
                   8299: 
                   8300:    if ($thisallowed=~/R/) {
1.620     albertel 8301:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8302:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8303: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8304: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8305: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8306: 	   }
                   8307: 	   return '';
1.54      www      8308:        }
1.53      www      8309:    }
1.30      www      8310: 
1.246     www      8311: # Restricted by state or randomout?
1.30      www      8312: 
1.52      www      8313:    if ($thisallowed=~/X/) {
1.620     albertel 8314:       if ($env{'acc.randomout'}) {
1.579     albertel 8315: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8316:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8317:             return ''; 
                   8318:          }
1.247     www      8319:       }
                   8320:       if (&condval($statecond)) {
1.52      www      8321: 	 return '2';
                   8322:       } else {
                   8323:          return '';
                   8324:       }
                   8325:    }
1.30      www      8326: 
1.766     albertel 8327:     if ($thisallowed eq 'A') {
                   8328: 	return 'A';
1.814     raeburn  8329:     } elsif ($thisallowed eq 'B') {
                   8330:         return 'B';
1.766     albertel 8331:     }
1.52      www      8332:    return 'F';
1.232     www      8333: }
1.1162    raeburn  8334: 
1.1172.2.13  raeburn  8335: # ------------------------------------------- Check construction space access
                   8336: 
                   8337: sub constructaccess {
                   8338:     my ($url,$setpriv)=@_;
                   8339: 
                   8340: # We do not allow editing of previous versions of files
                   8341:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8342: 
                   8343: # Get username and domain from URL
                   8344:     my ($ownername,$ownerdomain,$ownerhome);
                   8345: 
                   8346:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8347:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8348: 
                   8349: # The URL does not really point to any authorspace, forget it
                   8350:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8351: 
                   8352: # Now we need to see if the user has access to the authorspace of
                   8353: # $ownername at $ownerdomain
                   8354: 
                   8355:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8356: # Real author for this?
                   8357:        $ownerhome = $env{'user.home'};
                   8358:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8359:           return ($ownername,$ownerdomain,$ownerhome);
                   8360:        }
                   8361:     } else {
                   8362: # Co-author for this?
                   8363:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8364:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8365:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8366:             return ($ownername,$ownerdomain,$ownerhome);
                   8367:         }
                   8368:     }
                   8369: 
                   8370: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8371: # we might as well leave
                   8372:    unless ($setpriv) { return ''; }
                   8373: 
                   8374: # Backdoor access?
                   8375:     my $allowed=&allowed('eco',$ownerdomain);
                   8376: # Nope
                   8377:     unless ($allowed) { return ''; }
                   8378: # Looks like we may have access, but could be locked by the owner of the construction space
                   8379:     if ($allowed eq 'U') {
                   8380:         my %blocked=&get('environment',['domcoord.author'],
                   8381:                          $ownerdomain,$ownername);
                   8382: # Is blocked by owner
                   8383:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8384:     }
                   8385:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8386: # Grant temporary access
                   8387:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8388:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8389:         if (!$update) { $update = $then; }
                   8390:         my $refresh=$env{'user.refresh.time'};
                   8391:         if (!$refresh) { $refresh = $update; }
                   8392:         my $now = time;
                   8393:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8394:                            $now,'ca','constructaccess');
                   8395:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8396:         return($ownername,$ownerdomain,$ownerhome);
                   8397:     }
                   8398: # No business here
                   8399:     return '';
                   8400: }
                   8401: 
1.1172.2.66  raeburn  8402: # ----------------------------------------------------------- Content Blocking
                   8403: 
                   8404: {
                   8405: # Caches for faster Course Contents display where content blocking
                   8406: # is in operation (i.e., interval param set) for timed quiz.
                   8407: #
                   8408: # User for whom data are being temporarily cached.
                   8409: my $cacheduser='';
1.1172.2.126  raeburn  8410: # Course for which data are being temporarily cached.
                   8411: my $cachedcid='';
1.1172.2.66  raeburn  8412: # Cached blockers for this user (a hash of blocking items).
                   8413: my %cachedblockers=();
                   8414: # When the data were last cached.
                   8415: my $cachedlast='';
                   8416: 
                   8417: sub load_all_blockers {
1.1172.2.128  raeburn  8418:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8419:     if (($uname ne '') && ($udom ne '')) {
                   8420:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8421:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8422:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8423:             return;
                   8424:         }
                   8425:     }
                   8426:     $cachedlast=time;
                   8427:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8428:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8429:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8430:     return;
1.1172.2.66  raeburn  8431: }
                   8432: 
1.1162    raeburn  8433: sub get_comm_blocks {
                   8434:     my ($cdom,$cnum) = @_;
                   8435:     if ($cdom eq '' || $cnum eq '') {
                   8436:         return unless ($env{'request.course.id'});
                   8437:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8438:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8439:     }
                   8440:     my %commblocks;
                   8441:     my $hashid=$cdom.'_'.$cnum;
                   8442:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8443:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8444:         %commblocks = %{$blocksref};
                   8445:     } else {
                   8446:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8447:         my $cachetime = 600;
                   8448:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8449:     }
                   8450:     return %commblocks;
                   8451: }
                   8452: 
1.1172.2.66  raeburn  8453: sub get_commblock_resources {
                   8454:     my ($blocks) = @_;
                   8455:     my %blockers = ();
                   8456:     return %blockers unless ($env{'request.course.id'});
                   8457:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8458:     my %commblocks;
                   8459:     if (ref($blocks) eq 'HASH') {
                   8460:         %commblocks = %{$blocks};
                   8461:     } else {
                   8462:         %commblocks = &get_comm_blocks();
                   8463:     }
1.1172.2.66  raeburn  8464:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8465:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8466:     return %blockers unless (ref($navmap));
                   8467:     my $now = time;
1.1162    raeburn  8468:     foreach my $block (keys(%commblocks)) {
                   8469:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8470:             my ($start,$end) = ($1,$2);
                   8471:             if ($start <= $now && $end >= $now) {
                   8472:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8473:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8474:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8475:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8476:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8477:                             }
                   8478:                         }
                   8479:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8480:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8481:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8482:                             }
                   8483:                         }
                   8484:                     }
                   8485:                 }
                   8486:             }
                   8487:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8488:             my $item = $1;
1.1163    raeburn  8489:             my @to_test;
1.1162    raeburn  8490:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8491:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8492:                     my @interval;
                   8493:                     my $type = 'map';
                   8494:                     if ($item eq 'course') {
                   8495:                         $type = 'course';
                   8496:                         @interval=&EXT("resource.0.interval");
                   8497:                     } else {
                   8498:                         if ($item =~ /___\d+___/) {
                   8499:                             $type = 'resource';
                   8500:                             @interval=&EXT("resource.0.interval",$item);
                   8501:                             if (ref($navmap)) {
                   8502:                                 my $res = $navmap->getBySymb($item);
                   8503:                                 push(@to_test,$res);
                   8504:                             }
1.1162    raeburn  8505:                         } else {
1.1172.2.66  raeburn  8506:                             my $mapsymb = &symbread($item,1);
                   8507:                             if ($mapsymb) {
                   8508:                                 if (ref($navmap)) {
                   8509:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129  raeburn  8510:                                     if (ref($mapres)) {
                   8511:                                         my $first = $mapres->map_start();
                   8512:                                         my $finish = $mapres->map_finish();
                   8513:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8514:                                         if (ref($it)) {
                   8515:                                             my $res;
                   8516:                                             while ($res = $it->next(undef,1)) {
                   8517:                                                 next unless (ref($res));
                   8518:                                                 my $symb = $res->symb();
                   8519:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8520:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8521:                                                 if ($interval[1] eq 'map') {
                   8522:                                                     if ($res->answerable()) {
                   8523:                                                         push(@to_test,$res);
                   8524:                                                         last;
                   8525:                                                     }
                   8526:                                                 }
1.1162    raeburn  8527:                                             }
                   8528:                                         }
                   8529:                                     }
                   8530:                                 }
                   8531:                             }
                   8532:                         }
1.1172.2.66  raeburn  8533:                     }
                   8534:                     if ($interval[0] =~ /^\d+$/) {
                   8535:                         my $first_access;
                   8536:                         if ($type eq 'resource') {
                   8537:                             $first_access=&get_first_access($interval[1],$item);
                   8538:                         } elsif ($type eq 'map') {
                   8539:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8540:                         } else {
                   8541:                             $first_access=&get_first_access($interval[1]);
                   8542:                         }
                   8543:                         if ($first_access) {
                   8544:                             my $timesup = $first_access+$interval[0];
                   8545:                             if ($timesup > $now) {
                   8546:                                 my $activeblock;
                   8547:                                 foreach my $res (@to_test) {
                   8548:                                     if ($res->answerable()) {
                   8549:                                         $activeblock = 1;
                   8550:                                         last;
                   8551:                                     }
                   8552:                                 }
                   8553:                                 if ($activeblock) {
                   8554:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8555:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8556:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8557:                                          }
                   8558:                                     }
                   8559:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8560:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8561:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8562:                                         }
1.1162    raeburn  8563:                                     }
                   8564:                                 }
                   8565:                             }
                   8566:                         }
                   8567:                     }
                   8568:                 }
                   8569:             }
                   8570:         }
                   8571:     }
1.1172.2.66  raeburn  8572:     return %blockers;
1.1162    raeburn  8573: }
                   8574: 
1.1172.2.66  raeburn  8575: sub has_comm_blocking {
1.1172.2.128  raeburn  8576:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8577:     my @blockers;
                   8578:     return unless ($env{'request.course.id'});
                   8579:     return unless ($priv eq 'bre');
                   8580:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8581:     return if ($env{'request.state'} eq 'construct');
1.1172.2.128  raeburn  8582:     my %blockinfo;
                   8583:     if (ref($blocks) eq 'HASH') {
                   8584:         %blockinfo = &get_commblock_resources($blocks);
                   8585:     } else {
                   8586:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8587:         %blockinfo = %cachedblockers;
                   8588:     }
                   8589:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8590:     my (%possibles,@symbs);
                   8591:     if (!$symb) {
1.1172.2.128  raeburn  8592:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8593:     }
1.1172.2.66  raeburn  8594:     if ($symb) {
                   8595:         @symbs = ($symb);
                   8596:     } elsif (keys(%possibles)) {
                   8597:         @symbs = keys(%possibles);
                   8598:     }
                   8599:     my $noblock;
                   8600:     foreach my $symb (@symbs) {
                   8601:         last if ($noblock);
                   8602:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8603:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8604:             if ($block =~ /^firstaccess____(.+)$/) {
                   8605:                 my $item = $1;
1.1172.2.126  raeburn  8606:                 unless ($blocked) {
                   8607:                     if (($item eq $map) || ($item eq $symb)) {
                   8608:                         $noblock = 1;
                   8609:                         last;
                   8610:                     }
1.1172.2.66  raeburn  8611:                 }
1.1162    raeburn  8612:             }
1.1172.2.128  raeburn  8613:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8614:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8615:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8616:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8617:                             push(@blockers,$block);
                   8618:                         }
                   8619:                     }
                   8620:                 }
1.1172.2.128  raeburn  8621:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8622:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8623:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8624:                             push(@blockers,$block);
                   8625:                         }
1.1172.2.66  raeburn  8626:                     }
                   8627:                 }
1.1162    raeburn  8628:             }
                   8629:         }
                   8630:     }
1.1172.2.126  raeburn  8631:     unless ($noblock) {
                   8632:         return @blockers;
                   8633:     }
                   8634:     return;
1.1172.2.66  raeburn  8635: }
1.1162    raeburn  8636: }
                   8637: 
1.1172.2.66  raeburn  8638: # -------------------------------- Deversion and split uri into path an filename
                   8639: 
1.1133    foxr     8640: #
1.1172.2.66  raeburn  8641: #   Removes the version from a URI and
1.1133    foxr     8642: #   splits it in to its filename and path to the filename.
                   8643: #   Seems like File::Basename could have done this more clearly.
                   8644: #   Parameters:
                   8645: #      $uri   - input URI
                   8646: #   Returns:
                   8647: #     Two element list consisting of 
                   8648: #     $pathname  - the URI up to and excluding the trailing /
                   8649: #     $filename  - The part of the URI following the last /
                   8650: #  NOTE:
                   8651: #    Another realization of this is simply:
                   8652: #    use File::Basename;
                   8653: #    ...
                   8654: #    $uri = shift;
                   8655: #    $filename = basename($uri);
                   8656: #    $path     = dirname($uri);
                   8657: #    return ($filename, $path);
                   8658: #
                   8659: #     The implementation below is probably faster however.
                   8660: #
1.710     albertel 8661: sub split_uri_for_cond {
                   8662:     my $uri=&deversion(&declutter(shift));
                   8663:     my @uriparts=split(/\//,$uri);
                   8664:     my $filename=pop(@uriparts);
                   8665:     my $pathname=join('/',@uriparts);
                   8666:     return ($pathname,$filename);
                   8667: }
1.232     www      8668: # --------------------------------------------------- Is a resource on the map?
                   8669: 
                   8670: sub is_on_map {
1.710     albertel 8671:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8672:     #Trying to find the conditional for the file
1.620     albertel 8673:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8674: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8675:     if ($match) {
1.289     bowersj2 8676: 	return (1,$1);
                   8677:     } else {
1.434     www      8678: 	return (0,0);
1.289     bowersj2 8679:     }
1.12      www      8680: }
                   8681: 
1.427     www      8682: # --------------------------------------------------------- Get symb from alias
                   8683: 
                   8684: sub get_symb_from_alias {
                   8685:     my $symb=shift;
                   8686:     my ($map,$resid,$url)=&decode_symb($symb);
                   8687: # Already is a symb
                   8688:     if ($url) { return $symb; }
                   8689: # Must be an alias
                   8690:     my $aliassymb='';
                   8691:     my %bighash;
1.620     albertel 8692:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8693:                             &GDBM_READER(),0640)) {
                   8694:         my $rid=$bighash{'mapalias_'.$symb};
                   8695: 	if ($rid) {
                   8696: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8697: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8698: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8699: 	}
                   8700:         untie %bighash;
                   8701:     }
                   8702:     return $aliassymb;
                   8703: }
                   8704: 
1.12      www      8705: # ----------------------------------------------------------------- Define Role
                   8706: 
                   8707: sub definerole {
                   8708:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8709:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8710:     foreach my $role (split(':',$sysrole)) {
                   8711: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8712:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8713:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8714: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8715:                return "refused:s:$crole&$cqual"; 
                   8716:             }
                   8717:         }
1.191     harris41 8718:     }
1.800     albertel 8719:     foreach my $role (split(':',$domrole)) {
                   8720: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8721:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8722:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8723: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8724:                return "refused:d:$crole&$cqual"; 
                   8725:             }
                   8726:         }
1.191     harris41 8727:     }
1.800     albertel 8728:     foreach my $role (split(':',$courole)) {
                   8729: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8730:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8731:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8732: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8733:                return "refused:c:$crole&$cqual"; 
                   8734:             }
                   8735:         }
1.191     harris41 8736:     }
1.1172.2.84  raeburn  8737:     my $uhome;
                   8738:     if (($uname ne '') && ($udom ne '')) {
                   8739:         $uhome = &homeserver($uname,$udom);
                   8740:         return $uhome if ($uhome eq 'no_host');
                   8741:     } else {
                   8742:         $uname = $env{'user.name'};
                   8743:         $udom = $env{'user.domain'};
                   8744:         $uhome = $env{'user.home'};
                   8745:     }
1.620     albertel 8746:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8747:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8748:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8749:     return reply($command,$uhome);
1.12      www      8750:   } else {
                   8751:     return 'refused';
                   8752:   }
1.105     harris41 8753: }
                   8754: 
                   8755: # ---------------- Make a metadata query against the network of library servers
                   8756: 
                   8757: sub metadata_query {
1.1172.2.33  raeburn  8758:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8759:     my %rhash;
1.845     albertel 8760:     my %libserv = &all_library();
1.244     matthew  8761:     my @server_list = (defined($server_array) ? @$server_array
                   8762:                                               : keys(%libserv) );
                   8763:     for my $server (@server_list) {
1.1172.2.33  raeburn  8764:         my $domains = '';
                   8765:         if (ref($domains_hash) eq 'HASH') {
                   8766:             $domains = $domains_hash->{$server};    
                   8767:         }
1.118     harris41 8768: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8769: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8770: 	    $rhash{$server}=$reply;
                   8771: 	}
                   8772: 	else {
                   8773: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8774: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8775: 			     $server);
                   8776: 	    $rhash{$server}=$reply;
                   8777: 	}
1.112     harris41 8778:     }
1.118     harris41 8779:     return \%rhash;
1.240     www      8780: }
                   8781: 
                   8782: # ----------------------------------------- Send log queries and wait for reply
                   8783: 
                   8784: sub log_query {
                   8785:     my ($uname,$udom,$query,%filters)=@_;
                   8786:     my $uhome=&homeserver($uname,$udom);
                   8787:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8788:     my $uhost=&hostname($uhome);
1.800     albertel 8789:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8790:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8791:                        $uhome);
1.479     albertel 8792:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8793:     return get_query_reply($queryid);
                   8794: }
                   8795: 
1.818     raeburn  8796: # -------------------------- Update MySQL table for portfolio file
                   8797: 
                   8798: sub update_portfolio_table {
1.821     raeburn  8799:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8800:     if ($group ne '') {
                   8801:         $file_name =~s /^\Q$group\E//;
                   8802:     }
1.818     raeburn  8803:     my $homeserver = &homeserver($uname,$udom);
                   8804:     my $queryid=
1.821     raeburn  8805:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8806:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8807:     my $reply = &get_query_reply($queryid);
                   8808:     return $reply;
                   8809: }
                   8810: 
1.899     raeburn  8811: # -------------------------- Update MySQL allusers table
                   8812: 
                   8813: sub update_allusers_table {
                   8814:     my ($uname,$udom,$names) = @_;
                   8815:     my $homeserver = &homeserver($uname,$udom);
                   8816:     my $queryid=
                   8817:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8818:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8819:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8820:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8821:                'generation='.&escape($names->{'generation'}).'%%'.
                   8822:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8823:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8824:     return;
1.899     raeburn  8825: }
                   8826: 
1.508     raeburn  8827: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8828: 
                   8829: sub fetch_enrollment_query {
1.511     raeburn  8830:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8831:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8832:     my $maxtries = 1;
1.508     raeburn  8833:     if ($context eq 'automated') {
                   8834:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8835:         $sleep = 2;
                   8836:         $loopmax = 100;
1.547     raeburn  8837:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8838:     } else {
                   8839:         $homeserver = &homeserver($cnum,$dom);
                   8840:     }
1.838     albertel 8841:     my $host=&hostname($homeserver);
1.506     raeburn  8842:     my $cmd = '';
1.1000    raeburn  8843:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8844:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8845:     }
                   8846:     $cmd =~ s/%%$//;
                   8847:     $cmd = &escape($cmd);
                   8848:     my $query = 'fetchenrollment';
1.620     albertel 8849:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8850:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8851:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8852:         return 'error: '.$queryid;
                   8853:     }
1.1172.2.93  raeburn  8854:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8855:     my $tries = 1;
                   8856:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8857:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8858:         $tries ++;
                   8859:     }
1.526     raeburn  8860:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8861:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8862:     } else {
1.901     albertel 8863:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8864:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8865:             foreach my $line (@responses) {
                   8866:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8867:                 $$replyref{$key} = $value;
                   8868:             }
                   8869:         } else {
1.1117    foxr     8870:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8871:             foreach my $line (@responses) {
                   8872:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8873:                 $$replyref{$key} = $value;
                   8874:                 if ($value > 0) {
1.800     albertel 8875:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8876:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8877:                         my $destname = $pathname.'/'.$filename;
                   8878:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8879:                         if ($xml_classlist =~ /^error/) {
                   8880:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8881:                         } else {
1.1172.2.96  raeburn  8882:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8883:                                 print FILE &unescape($xml_classlist);
                   8884:                                 close(FILE);
1.526     raeburn  8885:                             } else {
                   8886:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8887:                             }
                   8888:                         }
                   8889:                     }
                   8890:                 }
                   8891:             }
                   8892:         }
                   8893:         return 'ok';
                   8894:     }
                   8895:     return 'error';
                   8896: }
                   8897: 
1.242     www      8898: sub get_query_reply {
1.1172.2.79  raeburn  8899:     my ($queryid,$sleep,$loopmax) = @_;
                   8900:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8901:         $sleep = 0.2;
                   8902:     }
                   8903:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8904:         $loopmax = 100;
                   8905:     }
1.1117    foxr     8906:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8907:     my $reply='';
1.1172.2.79  raeburn  8908:     for (1..$loopmax) {
                   8909: 	sleep($sleep);
1.240     www      8910:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8911: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8912: 		$reply = join('',<$fh>);
                   8913: 		close($fh);
1.240     www      8914: 	   } else { return 'error: reply_file_error'; }
1.242     www      8915:            return &unescape($reply);
                   8916: 	}
1.240     www      8917:     }
1.242     www      8918:     return 'timeout:'.$queryid;
1.240     www      8919: }
                   8920: 
                   8921: sub courselog_query {
1.241     www      8922: #
                   8923: # possible filters:
                   8924: # url: url or symb
                   8925: # username
                   8926: # domain
                   8927: # action: view, submit, grade
                   8928: # start: timestamp
                   8929: # end: timestamp
                   8930: #
1.240     www      8931:     my (%filters)=@_;
1.620     albertel 8932:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8933:     if ($filters{'url'}) {
                   8934: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8935:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8936:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8937:     }
1.620     albertel 8938:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8939:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8940:     return &log_query($cname,$cdom,'courselog',%filters);
                   8941: }
                   8942: 
                   8943: sub userlog_query {
1.858     raeburn  8944: #
                   8945: # possible filters:
                   8946: # action: log check role
                   8947: # start: timestamp
                   8948: # end: timestamp
                   8949: #
1.240     www      8950:     my ($uname,$udom,%filters)=@_;
                   8951:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8952: }
                   8953: 
1.506     raeburn  8954: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8955: 
                   8956: sub auto_run {
1.508     raeburn  8957:     my ($cnum,$cdom) = @_;
1.876     raeburn  8958:     my $response = 0;
                   8959:     my $settings;
                   8960:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8961:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8962:         $settings = $domconfig{'autoenroll'};
                   8963:         if ($settings->{'run'} eq '1') {
                   8964:             $response = 1;
                   8965:         }
                   8966:     } else {
1.934     raeburn  8967:         my $homeserver;
                   8968:         if (&is_course($cdom,$cnum)) {
                   8969:             $homeserver = &homeserver($cnum,$cdom);
                   8970:         } else {
                   8971:             $homeserver = &domain($cdom,'primary');
                   8972:         }
                   8973:         if ($homeserver ne 'no_host') {
                   8974:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8975:         }
1.876     raeburn  8976:     }
1.506     raeburn  8977:     return $response;
                   8978: }
1.776     albertel 8979: 
1.506     raeburn  8980: sub auto_get_sections {
1.508     raeburn  8981:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8982:     my $homeserver;
                   8983:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8984:         $homeserver = &homeserver($cnum,$cdom);
                   8985:     }
                   8986:     if (!defined($homeserver)) { 
                   8987:         if ($cdom =~ /^$match_domain$/) {
                   8988:             $homeserver = &domain($cdom,'primary');
                   8989:         }
                   8990:     }
                   8991:     my @secs;
                   8992:     if (defined($homeserver)) {
                   8993:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8994:         unless ($response eq 'refused') {
                   8995:             @secs = split(/:/,$response);
                   8996:         }
1.506     raeburn  8997:     }
                   8998:     return @secs;
                   8999: }
1.776     albertel 9000: 
1.506     raeburn  9001: sub auto_new_course {
1.1099    raeburn  9002:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9003:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9004:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9005:     return $response;
                   9006: }
1.776     albertel 9007: 
1.506     raeburn  9008: sub auto_validate_courseID {
1.508     raeburn  9009:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9010:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9011:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9012:     return $response;
                   9013: }
1.776     albertel 9014: 
1.1007    raeburn  9015: sub auto_validate_instcode {
1.1020    raeburn  9016:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9017:     my ($homeserver,$response);
                   9018:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9019:         $homeserver = &homeserver($cnum,$cdom);
                   9020:     }
                   9021:     if (!defined($homeserver)) {
                   9022:         if ($cdom =~ /^$match_domain$/) {
                   9023:             $homeserver = &domain($cdom,'primary');
                   9024:         }
                   9025:     }
1.1065    raeburn  9026:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9027:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9028:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9029:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9030: }
                   9031: 
1.506     raeburn  9032: sub auto_create_password {
1.873     raeburn  9033:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9034:     my ($homeserver,$response);
1.506     raeburn  9035:     my $create_passwd = 0;
                   9036:     my $authchk = '';
1.873     raeburn  9037:     if ($udom =~ /^$match_domain$/) {
                   9038:         $homeserver = &domain($udom,'primary');
                   9039:     }
                   9040:     if ($homeserver eq '') {
                   9041:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9042:             $homeserver = &homeserver($cnum,$cdom);
                   9043:         }
                   9044:     }
                   9045:     if ($homeserver eq '') {
                   9046:         $authchk = 'nodomain';
1.506     raeburn  9047:     } else {
1.873     raeburn  9048:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9049:         if ($response eq 'refused') {
                   9050:             $authchk = 'refused';
                   9051:         } else {
1.901     albertel 9052:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9053:         }
1.506     raeburn  9054:     }
                   9055:     return ($authparam,$create_passwd,$authchk);
                   9056: }
                   9057: 
1.706     raeburn  9058: sub auto_photo_permission {
                   9059:     my ($cnum,$cdom,$students) = @_;
                   9060:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9061:     my ($outcome,$perm_reqd,$conditions) = 
                   9062: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9063:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9064: 	return (undef,undef);
                   9065:     }
1.706     raeburn  9066:     return ($outcome,$perm_reqd,$conditions);
                   9067: }
                   9068: 
                   9069: sub auto_checkphotos {
                   9070:     my ($uname,$udom,$pid) = @_;
                   9071:     my $homeserver = &homeserver($uname,$udom);
                   9072:     my ($result,$resulttype);
                   9073:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9074: 				   &escape($uname).':'.&escape($pid),
                   9075: 				   $homeserver));
1.709     albertel 9076:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9077: 	return (undef,undef);
                   9078:     }
1.706     raeburn  9079:     if ($outcome) {
                   9080:         ($result,$resulttype) = split(/:/,$outcome);
                   9081:     } 
                   9082:     return ($result,$resulttype);
                   9083: }
                   9084: 
                   9085: sub auto_photochoice {
                   9086:     my ($cnum,$cdom) = @_;
                   9087:     my $homeserver = &homeserver($cnum,$cdom);
                   9088:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9089: 						       &escape($cdom),
                   9090: 						       $homeserver)));
1.709     albertel 9091:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9092: 	return (undef,undef);
                   9093:     }
1.706     raeburn  9094:     return ($update,$comment);
                   9095: }
                   9096: 
                   9097: sub auto_photoupdate {
                   9098:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9099:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9100:     my $host=&hostname($homeserver);
1.706     raeburn  9101:     my $cmd = '';
                   9102:     my $maxtries = 1;
1.800     albertel 9103:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9104:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9105:     }
                   9106:     $cmd =~ s/%%$//;
                   9107:     $cmd = &escape($cmd);
                   9108:     my $query = 'institutionalphotos';
                   9109:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9110:     unless ($queryid=~/^\Q$host\E\_/) {
                   9111:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9112:         return 'error: '.$queryid;
                   9113:     }
                   9114:     my $reply = &get_query_reply($queryid);
                   9115:     my $tries = 1;
                   9116:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9117:         $reply = &get_query_reply($queryid);
                   9118:         $tries ++;
                   9119:     }
                   9120:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9121:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9122:     } else {
                   9123:         my @responses = split(/:/,$reply);
                   9124:         my $outcome = shift(@responses); 
                   9125:         foreach my $item (@responses) {
                   9126:             my ($key,$value) = split(/=/,$item);
                   9127:             $$photo{$key} = $value;
                   9128:         }
                   9129:         return $outcome;
                   9130:     }
                   9131:     return 'error';
                   9132: }
                   9133: 
1.521     raeburn  9134: sub auto_instcode_format {
1.793     albertel 9135:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9136: 	$cat_order) = @_;
1.521     raeburn  9137:     my $courses = '';
1.772     raeburn  9138:     my @homeservers;
1.521     raeburn  9139:     if ($caller eq 'global') {
1.841     albertel 9140: 	my %servers = &get_servers($codedom,'library');
                   9141: 	foreach my $tryserver (keys(%servers)) {
                   9142: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9143: 		push(@homeservers,$tryserver);
                   9144: 	    }
1.584     raeburn  9145:         }
1.1022    raeburn  9146:     } elsif ($caller eq 'requests') {
                   9147:         if ($codedom =~ /^$match_domain$/) {
                   9148:             my $chome = &domain($codedom,'primary');
                   9149:             unless ($chome eq 'no_host') {
                   9150:                 push(@homeservers,$chome);
                   9151:             }
                   9152:         }
1.521     raeburn  9153:     } else {
1.772     raeburn  9154:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9155:     }
1.793     albertel 9156:     foreach my $code (keys(%{$instcodes})) {
                   9157:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9158:     }
                   9159:     chop($courses);
1.772     raeburn  9160:     my $ok_response = 0;
                   9161:     my $response;
                   9162:     while (@homeservers > 0 && $ok_response == 0) {
                   9163:         my $server = shift(@homeservers); 
                   9164:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9165:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9166:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9167: 		split(/:/,$response);
1.772     raeburn  9168:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9169:             push(@{$codetitles},&str2array($codetitles_str));
                   9170:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9171:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9172:             $ok_response = 1;
                   9173:         }
                   9174:     }
                   9175:     if ($ok_response) {
1.521     raeburn  9176:         return 'ok';
1.772     raeburn  9177:     } else {
                   9178:         return $response;
1.521     raeburn  9179:     }
                   9180: }
                   9181: 
1.792     raeburn  9182: sub auto_instcode_defaults {
                   9183:     my ($domain,$returnhash,$code_order) = @_;
                   9184:     my @homeservers;
1.841     albertel 9185: 
                   9186:     my %servers = &get_servers($domain,'library');
                   9187:     foreach my $tryserver (keys(%servers)) {
                   9188: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9189: 	    push(@homeservers,$tryserver);
                   9190: 	}
1.792     raeburn  9191:     }
1.841     albertel 9192: 
1.792     raeburn  9193:     my $response;
1.841     albertel 9194:     foreach my $server (@homeservers) {
1.792     raeburn  9195:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9196:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9197: 	
                   9198: 	foreach my $pair (split(/\&/,$response)) {
                   9199: 	    my ($name,$value)=split(/\=/,$pair);
                   9200: 	    if ($name eq 'code_order') {
                   9201: 		@{$code_order} = split(/\&/,&unescape($value));
                   9202: 	    } else {
                   9203: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9204: 	    }
                   9205: 	}
                   9206: 	return 'ok';
1.792     raeburn  9207:     }
1.841     albertel 9208: 
                   9209:     return $response;
1.1003    raeburn  9210: }
                   9211: 
                   9212: sub auto_possible_instcodes {
1.1007    raeburn  9213:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9214:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9215:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9216:         return;
                   9217:     }
1.1003    raeburn  9218:     my (@homeservers,$uhome);
                   9219:     if (defined(&domain($domain,'primary'))) {
                   9220:         $uhome=&domain($domain,'primary');
                   9221:         push(@homeservers,&domain($domain,'primary'));
                   9222:     } else {
                   9223:         my %servers = &get_servers($domain,'library');
                   9224:         foreach my $tryserver (keys(%servers)) {
                   9225:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9226:                 push(@homeservers,$tryserver);
                   9227:             }
                   9228:         }
                   9229:     }
                   9230:     my $response;
                   9231:     foreach my $server (@homeservers) {
                   9232:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9233:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9234:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9235:             split(':',$response);
                   9236:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9237:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9238:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9239:             my ($name,$value)=split('=',$item);
                   9240:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9241:         }
                   9242:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9243:             my ($name,$value)=split('=',$item);
                   9244:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9245:         }
                   9246:         return 'ok';
                   9247:     }
                   9248:     return $response;
                   9249: }
1.792     raeburn  9250: 
1.1010    raeburn  9251: sub auto_courserequest_checks {
                   9252:     my ($dom) = @_;
1.1020    raeburn  9253:     my ($homeserver,%validations);
                   9254:     if ($dom =~ /^$match_domain$/) {
                   9255:         $homeserver = &domain($dom,'primary');
                   9256:     }
                   9257:     unless ($homeserver eq 'no_host') {
                   9258:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9259:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9260:             my @items = split(/&/,$response);
                   9261:             foreach my $item (@items) {
                   9262:                 my ($key,$value) = split('=',$item);
                   9263:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9264:             }
                   9265:         }
                   9266:     }
1.1010    raeburn  9267:     return %validations; 
                   9268: }
                   9269: 
1.1020    raeburn  9270: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9271:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9272:     my ($homeserver,$response);
                   9273:     if ($dom =~ /^$match_domain$/) {
                   9274:         $homeserver = &domain($dom,'primary');
                   9275:     }
1.1172.2.43  raeburn  9276:     unless ($homeserver eq 'no_host') {
                   9277:         my $customdata;
                   9278:         if (ref($custominfo) eq 'HASH') {
                   9279:             $customdata = &freeze_escape($custominfo);
                   9280:         }
1.1020    raeburn  9281:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9282:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9283:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9284:                                     $customdata,$homeserver));
1.1020    raeburn  9285:     }
                   9286:     return $response;
                   9287: }
                   9288: 
1.777     albertel 9289: sub auto_validate_class_sec {
1.918     raeburn  9290:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9291:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9292:     my $ownerlist;
                   9293:     if (ref($owners) eq 'ARRAY') {
                   9294:         $ownerlist = join(',',@{$owners});
                   9295:     } else {
                   9296:         $ownerlist = $owners;
                   9297:     }
1.773     raeburn  9298:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9299:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9300:     return $response;
                   9301: }
                   9302: 
1.1172.2.94  raeburn  9303: sub auto_validate_instclasses {
                   9304:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9305:     my ($homeserver,%validations);
                   9306:     $homeserver = &homeserver($cnum,$cdom);
                   9307:     unless ($homeserver eq 'no_host') {
                   9308:         my $ownerlist;
                   9309:         if (ref($owners) eq 'ARRAY') {
                   9310:             $ownerlist = join(',',@{$owners});
                   9311:         } else {
                   9312:             $ownerlist = $owners;
                   9313:         }
                   9314:         if (ref($classesref) eq 'HASH') {
                   9315:             my $classes = &freeze_escape($classesref);
                   9316:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9317:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9318:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9319:                 my @items = split(/&/,$response);
                   9320:                 foreach my $item (@items) {
                   9321:                     my ($key,$value) = split('=',$item);
                   9322:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9323:                 }
                   9324:             }
                   9325:         }
                   9326:     }
                   9327:     return %validations;
                   9328: }
                   9329: 
1.1172.2.38  raeburn  9330: sub auto_crsreq_update {
                   9331:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9332:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9333:     my ($homeserver,%crsreqresponse);
                   9334:     if ($cdom =~ /^$match_domain$/) {
                   9335:         $homeserver = &domain($cdom,'primary');
                   9336:     }
                   9337:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9338:         my $info;
                   9339:         if (ref($inbound) eq 'HASH') {
                   9340:             $info = &freeze_escape($inbound);
                   9341:         }
                   9342:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9343:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9344:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9345:                             &escape($title).':'.&escape($code).':'.
                   9346:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9347:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9348:             my @items = split(/&/,$response);
                   9349:             foreach my $item (@items) {
                   9350:                 my ($key,$value) = split('=',$item);
                   9351:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9352:             }
                   9353:         }
                   9354:     }
                   9355:     return \%crsreqresponse;
                   9356: }
                   9357: 
1.1172.2.78  raeburn  9358: sub auto_export_grades {
                   9359:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9360:     my ($homeserver,%exportresponse);
                   9361:     if ($cdom =~ /^$match_domain$/) {
                   9362:         $homeserver = &domain($cdom,'primary');
                   9363:     }
                   9364:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9365:         my $info;
                   9366:         if (ref($inforef) eq 'HASH') {
                   9367:             $info = &freeze_escape($inforef);
                   9368:         }
                   9369:         if (ref($gradesref) eq 'HASH') {
                   9370:             my $grades = &freeze_escape($gradesref);
                   9371:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9372:                                 $info.':'.$grades,$homeserver);
                   9373:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9374:                 my @items = split(/&/,$response);
                   9375:                 foreach my $item (@items) {
                   9376:                     my ($key,$value) = split('=',$item);
                   9377:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9378:                 }
                   9379:             }
                   9380:         }
                   9381:     }
                   9382:     return \%exportresponse;
                   9383: }
                   9384: 
1.1172.2.68  raeburn  9385: sub check_instcode_cloning {
                   9386:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9387:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9388:         return;
                   9389:     }
                   9390:     my $canclone;
                   9391:     if (@{$code_order} > 0) {
                   9392:         my $instcoderegexp ='^';
                   9393:         my @clonecodes = split(/\&/,$cloner);
                   9394:         foreach my $item (@{$code_order}) {
                   9395:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9396:                 foreach my $pair (@clonecodes) {
                   9397:                     my ($key,$val) = split(/\=/,$pair,2);
                   9398:                     $val = &unescape($val);
                   9399:                     if ($key eq $item) {
                   9400:                         $instcoderegexp .= '('.$val.')';
                   9401:                         last;
                   9402:                     }
                   9403:                 }
                   9404:             } else {
                   9405:                 $instcoderegexp .= $codedefaults->{$item};
                   9406:             }
                   9407:         }
                   9408:         $instcoderegexp .= '$';
                   9409:         my (@from,@to);
                   9410:         eval {
                   9411:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9412:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9413:         };
                   9414:         if ((@from > 0) && (@to > 0)) {
                   9415:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9416:             if (!@diffs) {
                   9417:                 $canclone = 1;
                   9418:             }
                   9419:         }
                   9420:     }
                   9421:     return $canclone;
                   9422: }
                   9423: 
                   9424: sub default_instcode_cloning {
                   9425:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9426:     my (%codedefaults,@code_order,$canclone);
                   9427:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9428:         %codedefaults = %{$codedefaultsref};
                   9429:         @code_order = @{$codeorderref};
                   9430:     } elsif ($clonedom) {
                   9431:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9432:     }
                   9433:     if (($domdefclone) && (@code_order)) {
                   9434:         my @clonecodes = split(/\+/,$domdefclone);
                   9435:         my $instcoderegexp ='^';
                   9436:         foreach my $item (@code_order) {
                   9437:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9438:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9439:             } else {
                   9440:                 $instcoderegexp .= $codedefaults{$item};
                   9441:             }
                   9442:         }
                   9443:         $instcoderegexp .= '$';
                   9444:         my (@from,@to);
                   9445:         eval {
                   9446:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9447:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9448:         };
                   9449:         if ((@from > 0) && (@to > 0)) {
                   9450:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9451:             if (!@diffs) {
                   9452:                 $canclone = 1;
                   9453:             }
                   9454:         }
                   9455:     }
                   9456:     return $canclone;
                   9457: }
                   9458: 
1.679     raeburn  9459: # ------------------------------------------------------- Course Group routines
                   9460: 
                   9461: sub get_coursegroups {
1.809     raeburn  9462:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9463:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9464: }
                   9465: 
1.679     raeburn  9466: sub modify_coursegroup {
                   9467:     my ($cdom,$cnum,$groupsettings) = @_;
                   9468:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9469: }
                   9470: 
1.809     raeburn  9471: sub toggle_coursegroup_status {
                   9472:     my ($cdom,$cnum,$group,$action) = @_;
                   9473:     my ($from_namespace,$to_namespace);
                   9474:     if ($action eq 'delete') {
                   9475:         $from_namespace = 'coursegroups';
                   9476:         $to_namespace = 'deleted_groups';
                   9477:     } else {
                   9478:         $from_namespace = 'deleted_groups';
                   9479:         $to_namespace = 'coursegroups';
                   9480:     }
                   9481:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9482:     if (my $tmp = &error(%curr_group)) {
                   9483:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9484:         return ('read error',$tmp);
                   9485:     } else {
                   9486:         my %savedsettings = %curr_group; 
1.809     raeburn  9487:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9488:         my $deloutcome;
                   9489:         if ($result eq 'ok') {
1.809     raeburn  9490:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9491:         } else {
                   9492:             return ('write error',$result);
                   9493:         }
                   9494:         if ($deloutcome eq 'ok') {
                   9495:             return 'ok';
                   9496:         } else {
                   9497:             return ('delete error',$deloutcome);
                   9498:         }
                   9499:     }
                   9500: }
                   9501: 
1.679     raeburn  9502: sub modify_group_roles {
1.957     raeburn  9503:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9504:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9505:     my $role = 'gr/'.&escape($userprivs);
                   9506:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9507:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9508:     if ($result eq 'ok') {
                   9509:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9510:     }
1.679     raeburn  9511:     return $result;
                   9512: }
                   9513: 
                   9514: sub modify_coursegroup_membership {
                   9515:     my ($cdom,$cnum,$membership) = @_;
                   9516:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9517:     return $result;
                   9518: }
                   9519: 
1.682     raeburn  9520: sub get_active_groups {
                   9521:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9522:     my $now = time;
                   9523:     my %groups = ();
                   9524:     foreach my $key (keys(%env)) {
1.811     albertel 9525:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9526:             my ($start,$end) = split(/\./,$env{$key});
                   9527:             if (($end!=0) && ($end<$now)) { next; }
                   9528:             if (($start!=0) && ($start>$now)) { next; }
                   9529:             if ($1 eq $cdom && $2 eq $cnum) {
                   9530:                 $groups{$3} = $env{$key} ;
                   9531:             }
                   9532:         }
                   9533:     }
                   9534:     return %groups;
                   9535: }
                   9536: 
1.683     raeburn  9537: sub get_group_membership {
                   9538:     my ($cdom,$cnum,$group) = @_;
                   9539:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9540: }
                   9541: 
                   9542: sub get_users_groups {
                   9543:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9544:     my @usersgroups;
1.683     raeburn  9545:     my $cachetime=1800;
                   9546: 
                   9547:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9548:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9549:     if (defined($cached)) {
1.734     albertel 9550:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9551:     } else {  
                   9552:         $grouplist = '';
1.816     raeburn  9553:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9554:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9555:         my $access_end = $env{'course.'.$courseid.
                   9556:                               '.default_enrollment_end_date'};
                   9557:         my $now = time;
                   9558:         foreach my $key (keys(%roleshash)) {
                   9559:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9560:                 my $group = $1;
                   9561:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9562:                     my $start = $2;
                   9563:                     my $end = $1;
                   9564:                     if ($start == -1) { next; } # deleted from group
                   9565:                     if (($start!=0) && ($start>$now)) { next; }
                   9566:                     if (($end!=0) && ($end<$now)) {
                   9567:                         if ($access_end && $access_end < $now) {
                   9568:                             if ($access_end - $end < 86400) {
                   9569:                                 push(@usersgroups,$group);
1.733     raeburn  9570:                             }
                   9571:                         }
1.817     raeburn  9572:                         next;
1.733     raeburn  9573:                     }
1.817     raeburn  9574:                     push(@usersgroups,$group);
1.683     raeburn  9575:                 }
                   9576:             }
                   9577:         }
1.817     raeburn  9578:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9579:         $grouplist = join(':',@usersgroups);
                   9580:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9581:     }
1.733     raeburn  9582:     return @usersgroups;
1.683     raeburn  9583: }
                   9584: 
                   9585: sub devalidate_getgroups_cache {
                   9586:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9587:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9588: 
1.683     raeburn  9589:     my $hashid="$udom:$uname:$courseid";
                   9590:     &devalidate_cache_new('getgroups',$hashid);
                   9591: }
                   9592: 
1.12      www      9593: # ------------------------------------------------------------------ Plain Text
                   9594: 
                   9595: sub plaintext {
1.988     raeburn  9596:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9597:     if ($short =~ m{^cr/}) {
1.758     albertel 9598: 	return (split('/',$short))[-1];
                   9599:     }
1.742     raeburn  9600:     if (!defined($cid)) {
                   9601:         $cid = $env{'request.course.id'};
                   9602:     }
                   9603:     my %rolenames = (
1.1008    raeburn  9604:                       Course    => 'std',
                   9605:                       Community => 'alt1',
1.742     raeburn  9606:                     );
1.1037    raeburn  9607:     if ($cid ne '') {
                   9608:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9609:             unless ($forcedefault) {
                   9610:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9611:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9612:                 return &Apache::lonlocal::mt($roletext);
                   9613:             }
                   9614:         }
                   9615:     }
                   9616:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9617:         (defined($rolenames{$type})) && 
                   9618:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9619:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9620:     } elsif ($cid ne '') {
                   9621:         my $crstype = $env{'course.'.$cid.'.type'};
                   9622:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9623:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9624:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9625:         }
1.742     raeburn  9626:     }
1.1037    raeburn  9627:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9628: }
                   9629: 
                   9630: # ----------------------------------------------------------------- Assign Role
                   9631: 
                   9632: sub assignrole {
1.957     raeburn  9633:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9634:         $context)=@_;
1.21      www      9635:     my $mrole;
                   9636:     if ($role =~ /^cr\//) {
1.393     www      9637:         my $cwosec=$url;
1.811     albertel 9638:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9639: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9640:            my $refused = 1;
                   9641:            if ($context eq 'requestcourses') {
                   9642:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9643:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9644:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9645:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9646:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9647:                            if ($crsenv{'internal.courseowner'} eq
                   9648:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9649:                                $refused = '';
                   9650:                            }
                   9651:                        }
                   9652:                    }
                   9653:                }
                   9654:            }
                   9655:            if ($refused) {
                   9656:                &logthis('Refused custom assignrole: '.
                   9657:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9658:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9659:                return 'refused';
                   9660:            }
1.104     www      9661:         }
1.21      www      9662:         $mrole='cr';
1.678     raeburn  9663:     } elsif ($role =~ /^gr\//) {
                   9664:         my $cwogrp=$url;
1.811     albertel 9665:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9666:         unless (&allowed('mdg',$cwogrp)) {
                   9667:             &logthis('Refused group assignrole: '.
                   9668:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9669:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9670:             return 'refused';
                   9671:         }
                   9672:         $mrole='gr';
1.21      www      9673:     } else {
1.82      www      9674:         my $cwosec=$url;
1.811     albertel 9675:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9676:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9677:             my $refused;
                   9678:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9679:                 if (!(&allowed('c'.$role,$url))) {
                   9680:                     $refused = 1;
                   9681:                 }
                   9682:             } else {
                   9683:                 $refused = 1;
                   9684:             }
1.947     raeburn  9685:             if ($refused) {
1.1045    raeburn  9686:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9687:                 if (!$selfenroll && $context eq 'course') {
                   9688:                     my %crsenv;
                   9689:                     if ($role eq 'cc' || $role eq 'co') {
                   9690:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9691:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9692:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9693:                                 if ($crsenv{'internal.courseowner'} eq 
                   9694:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9695:                                     $refused = '';
                   9696:                                 }
                   9697:                             }
                   9698:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9699:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9700:                                 if ($crsenv{'internal.courseowner'} eq 
                   9701:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9702:                                     $refused = '';
                   9703:                                 }
                   9704:                             }
                   9705:                         }
                   9706:                     }
                   9707:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9708:                     $refused = '';
1.1017    raeburn  9709:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9710:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9711:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9712:                         my $wrongcc;
                   9713:                         if ($cnum =~ /^$match_community$/) {
                   9714:                             $wrongcc = 1 if ($role eq 'cc');
                   9715:                         } else {
                   9716:                             $wrongcc = 1 if ($role eq 'co');
                   9717:                         }
                   9718:                         unless ($wrongcc) {
                   9719:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9720:                             if ($crsenv{'internal.courseowner'} eq 
                   9721:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9722:                                 $refused = '';
                   9723:                             }
1.1017    raeburn  9724:                         }
                   9725:                     }
1.1172.2.9  raeburn  9726:                 } elsif ($context eq 'requestauthor') {
                   9727:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9728:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9729:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9730:                             $refused = '';
                   9731:                         } else {
                   9732:                             my %domdefaults = &get_domain_defaults($udom);
                   9733:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9734:                                 my $checkbystatus;
                   9735:                                 if ($env{'user.adv'}) {
                   9736:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9737:                                     if ($disposition eq 'automatic') {
                   9738:                                         $refused = '';
                   9739:                                     } elsif ($disposition eq '') {
                   9740:                                         $checkbystatus = 1;
                   9741:                                     }
                   9742:                                 } else {
                   9743:                                     $checkbystatus = 1;
                   9744:                                 }
                   9745:                                 if ($checkbystatus) {
                   9746:                                     if ($env{'environment.inststatus'}) {
                   9747:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9748:                                         foreach my $type (@inststatuses) {
                   9749:                                             if (($type ne '') &&
                   9750:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9751:                                                 $refused = '';
                   9752:                                             }
                   9753:                                         }
                   9754:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9755:                                         $refused = '';
                   9756:                                     }
                   9757:                                 }
                   9758:                             }
                   9759:                         }
                   9760:                     }
1.1017    raeburn  9761:                 }
                   9762:                 if ($refused) {
1.947     raeburn  9763:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9764:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9765: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9766:                     return 'refused';
                   9767:                 }
1.932     raeburn  9768:             }
1.1131    raeburn  9769:         } elsif ($role eq 'au') {
                   9770:             if ($url ne '/'.$udom.'/') {
                   9771:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9772:                          ' to assign author role for '.$uname.':'.$udom.
                   9773:                          ' in domain: '.$url.' refused (wrong domain).');
                   9774:                 return 'refused';
                   9775:             }
1.104     www      9776:         }
1.21      www      9777:         $mrole=$role;
                   9778:     }
1.620     albertel 9779:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9780:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9781:     if ($end) { $command.='_'.$end; }
1.21      www      9782:     if ($start) {
                   9783: 	if ($end) { 
1.81      www      9784:            $command.='_'.$start; 
1.21      www      9785:         } else {
1.81      www      9786:            $command.='_0_'.$start;
1.21      www      9787:         }
                   9788:     }
1.739     raeburn  9789:     my $origstart = $start;
                   9790:     my $origend = $end;
1.957     raeburn  9791:     my $delflag;
1.357     www      9792: # actually delete
                   9793:     if ($deleteflag) {
1.373     www      9794: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9795: # modify command to delete the role
1.620     albertel 9796:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9797:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9798: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9799: # set start and finish to negative values for userrolelog
                   9800:            $start=-1;
                   9801:            $end=-1;
1.957     raeburn  9802:            $delflag = 1;
1.357     www      9803:         }
                   9804:     }
                   9805: # send command
1.349     www      9806:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9807: # log new user role if status is ok
1.349     www      9808:     if ($answer eq 'ok') {
1.663     raeburn  9809: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9810:         if (($role eq 'cc') || ($role eq 'in') ||
                   9811:             ($role eq 'ep') || ($role eq 'ad') ||
                   9812:             ($role eq 'ta') || ($role eq 'st') ||
                   9813:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9814:             ($role eq 'co')) {
1.1172.2.13  raeburn  9815: # for course roles, perform group memberships changes triggered by role change.
                   9816:             unless ($role =~ /^gr/) {
                   9817:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9818:                                                  $origstart,$selfenroll,$context);
                   9819:             }
1.1172.2.9  raeburn  9820:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9821:                            $selfenroll,$context);
                   9822:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9823:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9824:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9825:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9826:                            $context);
                   9827:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9828:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9829:                              $context);
                   9830:         }
1.1053    raeburn  9831:         if ($role eq 'cc') {
                   9832:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9833:         }
1.349     www      9834:     }
                   9835:     return $answer;
1.169     harris41 9836: }
                   9837: 
1.1053    raeburn  9838: sub autoupdate_coowners {
                   9839:     my ($url,$end,$start,$uname,$udom) = @_;
                   9840:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9841:     if (($cdom ne '') && ($cnum ne '')) {
                   9842:         my $now = time;
                   9843:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9844:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9845:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9846:             my $instcode = $coursehash{'internal.coursecode'};
                   9847:             if ($instcode ne '') {
1.1056    raeburn  9848:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9849:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9850:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9851:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9852:                         if ($result eq 'valid') {
                   9853:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9854:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9855:                                     push(@newcoowners,$coowner);
                   9856:                                 }
                   9857:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9858:                                     push(@newcoowners,$uname.':'.$udom);
                   9859:                                 }
                   9860:                                 @newcoowners = sort(@newcoowners);
                   9861:                             } else {
                   9862:                                 push(@newcoowners,$uname.':'.$udom);
                   9863:                             }
                   9864:                         } else {
                   9865:                             if ($coursehash{'internal.co-owners'}) {
                   9866:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9867:                                     unless ($coowner eq $uname.':'.$udom) {
                   9868:                                         push(@newcoowners,$coowner);
                   9869:                                     }
                   9870:                                 }
                   9871:                                 unless (@newcoowners > 0) {
                   9872:                                     $delcoowners = 1;
                   9873:                                     $coowners = '';
                   9874:                                 }
                   9875:                             }
                   9876:                         }
                   9877:                         if (@newcoowners || $delcoowners) {
                   9878:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9879:                                             $delcoowners,@newcoowners);
                   9880:                         }
                   9881:                     }
                   9882:                 }
                   9883:             }
                   9884:         }
                   9885:     }
                   9886: }
                   9887: 
                   9888: sub store_coowners {
                   9889:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9890:     my $cid = $cdom.'_'.$cnum;
                   9891:     my ($coowners,$delresult,$putresult);
                   9892:     if (@newcoowners) {
                   9893:         $coowners = join(',',@newcoowners);
                   9894:         my %coownershash = (
                   9895:                             'internal.co-owners' => $coowners,
                   9896:                            );
                   9897:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9898:         if ($putresult eq 'ok') {
                   9899:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9900:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9901:             }
                   9902:         }
                   9903:     }
                   9904:     if ($delcoowners) {
                   9905:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9906:         if ($delresult eq 'ok') {
                   9907:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9908:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9909:             }
                   9910:         }
                   9911:     }
                   9912:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9913:         my %crsinfo =
                   9914:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9915:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9916:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9917:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9918:         }
                   9919:     }
                   9920: }
                   9921: 
1.169     harris41 9922: # -------------------------------------------------- Modify user authentication
1.197     www      9923: # Overrides without validation
                   9924: 
1.169     harris41 9925: sub modifyuserauth {
                   9926:     my ($udom,$uname,$umode,$upass)=@_;
                   9927:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9928:     my $allowed;
                   9929:     if (&allowed('mau',$udom)) {
                   9930:         $allowed = 1;
                   9931:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9932:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9933:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9934:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9935:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9936:         if (($cdom ne '') && ($cnum ne '')) {
                   9937:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9938:             if ($is_owner) {
                   9939:                 $allowed = 1;
                   9940:             }
                   9941:         }
                   9942:     }
                   9943:     unless ($allowed) { return 'refused'; }
1.197     www      9944:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9945:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9946:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9947:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9948: 		     &escape($upass),$uhome);
1.620     albertel 9949:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9950:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9951:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9952:     &log($udom,,$uname,$uhome,
1.620     albertel 9953:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9954:                                      $env{'user.name'}.', '.$umode.
1.197     www      9955:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9956:     unless ($reply eq 'ok') {
1.197     www      9957:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9958: 	return 'error: '.$reply;
                   9959:     }   
1.170     harris41 9960:     return 'ok';
1.80      www      9961: }
                   9962: 
1.81      www      9963: # --------------------------------------------------------------- Modify a user
1.80      www      9964: 
1.81      www      9965: sub modifyuser {
1.206     matthew  9966:     my ($udom,    $uname, $uid,
                   9967:         $umode,   $upass, $first,
                   9968:         $middle,  $last,  $gene,
1.1058    raeburn  9969:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9970:     $udom= &LONCAPA::clean_domain($udom);
                   9971:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9972:     my $showcandelete = 'none';
                   9973:     if (ref($candelete) eq 'ARRAY') {
                   9974:         if (@{$candelete} > 0) {
                   9975:             $showcandelete = join(', ',@{$candelete});
                   9976:         }
                   9977:     }
1.81      www      9978:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9979:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9980: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9981:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9982:                                      ' desiredhome not specified'). 
1.620     albertel 9983:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9984:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9985:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9986:     my $newuser;
                   9987:     if ($uhome eq 'no_host') {
                   9988:         $newuser = 1;
                   9989:     }
1.80      www      9990: # ----------------------------------------------------------------- Create User
1.406     albertel 9991:     if (($uhome eq 'no_host') && 
                   9992: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9993:         my $unhome='';
1.844     albertel 9994:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9995:             $unhome = $desiredhome;
1.620     albertel 9996: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9997: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9998:         } else { # load balancing routine for determining $unhome
1.81      www      9999:             my $loadm=10000000;
1.841     albertel 10000: 	    my %servers = &get_servers($udom,'library');
                   10001: 	    foreach my $tryserver (keys(%servers)) {
                   10002: 		my $answer=reply('load',$tryserver);
                   10003: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10004: 		    $loadm=$answer;
                   10005: 		    $unhome=$tryserver;
                   10006: 		}
1.80      www      10007: 	    }
                   10008:         }
                   10009:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10010: 	    return 'error: unable to find a home server for '.$uname.
                   10011:                    ' in domain '.$udom;
1.80      www      10012:         }
                   10013:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10014:                          &escape($upass),$unhome);
                   10015: 	unless ($reply eq 'ok') {
                   10016:             return 'error: '.$reply;
                   10017:         }   
1.230     stredwic 10018:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10019:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10020: 	    return 'error: unable verify users home machine.';
1.80      www      10021:         }
1.209     matthew  10022:     }   # End of creation of new user
1.80      www      10023: # ---------------------------------------------------------------------- Add ID
                   10024:     if ($uid) {
                   10025:        $uid=~tr/A-Z/a-z/;
                   10026:        my %uidhash=&idrget($udom,$uname);
1.196     www      10027:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10028:          && (!$forceid)) {
1.80      www      10029: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10030: 	      return 'error: user id "'.$uid.'" does not match '.
                   10031:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10032:           }
                   10033:        } else {
                   10034: 	  &idput($udom,($uname => $uid));
                   10035:        }
                   10036:     }
                   10037: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10038:     my @tmp=&get('environment',
1.899     raeburn  10039: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10040:                     'permanentemail','inststatus'],
1.134     albertel 10041: 		   $udom,$uname);
1.1075    raeburn  10042:     my (%names,%oldnames);
1.313     matthew  10043:     if ($tmp[0] =~ m/^error:.*/) { 
                   10044:         %names=(); 
                   10045:     } else {
                   10046:         %names = @tmp;
1.1075    raeburn  10047:         %oldnames = %names;
1.313     matthew  10048:     }
1.388     www      10049: #
1.1058    raeburn  10050: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10051: # of users did not contain them), do not overwrite existing values
                   10052: # unless field is in $candelete array ref.  
                   10053: #
                   10054: 
                   10055:     my @fields = ('firstname','middlename','lastname','generation',
                   10056:                   'permanentemail','id');
                   10057:     my %newvalues;
                   10058:     if (ref($candelete) eq 'ARRAY') {
                   10059:         foreach my $field (@fields) {
                   10060:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10061:                 if ($field eq 'firstname') {
                   10062:                     $names{$field} = $first;
                   10063:                 } elsif ($field eq 'middlename') {
                   10064:                     $names{$field} = $middle;
                   10065:                 } elsif ($field eq 'lastname') {
                   10066:                     $names{$field} = $last;
                   10067:                 } elsif ($field eq 'generation') { 
                   10068:                     $names{$field} = $gene;
                   10069:                 } elsif ($field eq 'permanentemail') {
                   10070:                     $names{$field} = $email;
                   10071:                 } elsif ($field eq 'id') {
                   10072:                     $names{$field}  = $uid;
                   10073:                 }
                   10074:             }
                   10075:         }
                   10076:     }
1.388     www      10077:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10078:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10079:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10080:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10081:     if ($email) {
                   10082:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10083:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10084:     }
1.899     raeburn  10085:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10086:     if (defined($inststatus)) {
                   10087:         $names{'inststatus'} = '';
                   10088:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10089:         if (ref($usertypes) eq 'HASH') {
                   10090:             my @okstatuses; 
                   10091:             foreach my $item (split(/:/,$inststatus)) {
                   10092:                 if (defined($usertypes->{$item})) {
                   10093:                     push(@okstatuses,$item);  
                   10094:                 }
                   10095:             }
                   10096:             if (@okstatuses) {
                   10097:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10098:             }
                   10099:         }
                   10100:     }
1.1075    raeburn  10101:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10102:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10103:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10104:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10105:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10106:     } else {
                   10107:         $logmsg .= ' during self creation';
                   10108:     }
1.1075    raeburn  10109:     my $changed;
                   10110:     if ($newuser) {
                   10111:         $changed = 1;
                   10112:     } else {
                   10113:         foreach my $field (@fields) {
                   10114:             if ($names{$field} ne $oldnames{$field}) {
                   10115:                 $changed = 1;
                   10116:                 last;
                   10117:             }
                   10118:         }
                   10119:     }
                   10120:     unless ($changed) {
                   10121:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10122:         &logthis($logmsg);
                   10123:         return 'ok';
                   10124:     }
                   10125:     my $reply = &put('environment', \%names, $udom,$uname);
                   10126:     if ($reply ne 'ok') { 
                   10127:         return 'error: '.$reply;
                   10128:     }
1.1087    raeburn  10129:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10130:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10131:     }
1.1075    raeburn  10132:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10133:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10134:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10135:     &logthis($logmsg);
1.134     albertel 10136:     return 'ok';
1.80      www      10137: }
                   10138: 
1.81      www      10139: # -------------------------------------------------------------- Modify student
1.80      www      10140: 
1.81      www      10141: sub modifystudent {
                   10142:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10143:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10144:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10145:     if (!$cid) {
1.620     albertel 10146: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10147: 	    return 'not_in_class';
                   10148: 	}
1.80      www      10149:     }
                   10150: # --------------------------------------------------------------- Make the user
1.81      www      10151:     my $reply=&modifyuser
1.209     matthew  10152: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10153:          $desiredhome,$email,$inststatus);
1.80      www      10154:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10155:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10156:     # student's environment
1.297     matthew  10157:     $uid = undef if (!$forceid);
1.455     albertel 10158:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10159: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10160:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10161:     return $reply;
                   10162: }
                   10163: 
                   10164: sub modify_student_enrollment {
1.1172.2.23  raeburn  10165:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10166:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10167:     my ($cdom,$cnum,$chome);
                   10168:     if (!$cid) {
1.620     albertel 10169: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10170: 	    return 'not_in_class';
                   10171: 	}
1.620     albertel 10172: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10173: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10174:     } else {
                   10175: 	($cdom,$cnum)=split(/_/,$cid);
                   10176:     }
1.620     albertel 10177:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10178:     if (!$chome) {
1.457     raeburn  10179: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10180:     }
1.455     albertel 10181:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10182:     # Make sure the user exists
1.81      www      10183:     my $uhome=&homeserver($uname,$udom);
                   10184:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10185: 	return 'error: no such user';
                   10186:     }
1.297     matthew  10187:     # Get student data if we were not given enough information
                   10188:     if (!defined($first)  || $first  eq '' || 
                   10189:         !defined($last)   || $last   eq '' || 
                   10190:         !defined($uid)    || $uid    eq '' || 
                   10191:         !defined($middle) || $middle eq '' || 
                   10192:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10193:         # They did not supply us with enough data to enroll the student, so
                   10194:         # we need to pick up more information.
1.297     matthew  10195:         my %tmp = &get('environment',
1.294     matthew  10196:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10197:                        ,$udom,$uname);
                   10198: 
1.800     albertel 10199:         #foreach my $key (keys(%tmp)) {
                   10200:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10201:         #}
1.294     matthew  10202:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10203:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10204:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10205:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10206:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10207:     }
1.556     albertel 10208:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10209:     my $user = "$uname:$udom";
                   10210:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10211:     my $reply=cput('classlist',
1.1148    raeburn  10212: 		   {$user => 
1.1172.2.76  raeburn  10213: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10214: 		   $cdom,$cnum);
1.1148    raeburn  10215:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10216:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10217:     } else { 
1.81      www      10218: 	return 'error: '.$reply;
                   10219:     }
1.297     matthew  10220:     # Add student role to user
1.83      www      10221:     my $uurl='/'.$cid;
1.81      www      10222:     $uurl=~s/\_/\//g;
                   10223:     if ($usec) {
                   10224: 	$uurl.='/'.$usec;
                   10225:     }
1.1148    raeburn  10226:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10227:                              $selfenroll,$context);
                   10228:     if ($result ne 'ok') {
                   10229:         if ($old_entry{$user} ne '') {
                   10230:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10231:         } else {
                   10232:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10233:         }
                   10234:     }
                   10235:     return $result; 
1.21      www      10236: }
                   10237: 
1.556     albertel 10238: sub format_name {
                   10239:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10240:     my $name;
                   10241:     if ($first ne 'lastname') {
                   10242: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10243:     } else {
                   10244: 	if ($lastname=~/\S/) {
                   10245: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10246: 	    $name=~s/\s+,/,/;
                   10247: 	} else {
                   10248: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10249: 	}
                   10250:     }
                   10251:     $name=~s/^\s+//;
                   10252:     $name=~s/\s+$//;
                   10253:     $name=~s/\s+/ /g;
                   10254:     return $name;
                   10255: }
                   10256: 
1.84      www      10257: # ------------------------------------------------- Write to course preferences
                   10258: 
                   10259: sub writecoursepref {
                   10260:     my ($courseid,%prefs)=@_;
                   10261:     $courseid=~s/^\///;
                   10262:     $courseid=~s/\_/\//g;
                   10263:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10264:     my $chome=homeserver($cnum,$cdomain);
                   10265:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10266: 	return 'error: no such course';
                   10267:     }
                   10268:     my $cstring='';
1.800     albertel 10269:     foreach my $pref (keys(%prefs)) {
                   10270: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10271:     }
1.84      www      10272:     $cstring=~s/\&$//;
                   10273:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10274: }
                   10275: 
                   10276: # ---------------------------------------------------------- Make/modify course
                   10277: 
                   10278: sub createcourse {
1.741     raeburn  10279:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10280:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10281:     $url=&declutter($url);
                   10282:     my $cid='';
1.1028    raeburn  10283:     if ($context eq 'requestcourses') {
                   10284:         my $can_create = 0;
                   10285:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10286:         if ($udom eq $ownerdom) {
                   10287:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10288:                                   $context)) {
                   10289:                 $can_create = 1;
                   10290:             }
                   10291:         } else {
                   10292:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10293:                                            $category);
                   10294:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10295:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10296:                 if (@curr > 0) {
                   10297:                     my @options = qw(approval validate autolimit);
                   10298:                     my $optregex = join('|',@options);
                   10299:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10300:                         $can_create = 1;
                   10301:                     }
                   10302:                 }
                   10303:             }
                   10304:         }
                   10305:         if ($can_create) {
                   10306:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10307:                 unless (&allowed('ccc',$udom)) {
                   10308:                     return 'refused'; 
                   10309:                 }
1.1017    raeburn  10310:             }
                   10311:         } else {
                   10312:             return 'refused';
                   10313:         }
1.1028    raeburn  10314:     } elsif (!&allowed('ccc',$udom)) {
                   10315:         return 'refused';
1.84      www      10316:     }
1.1011    raeburn  10317: # --------------------------------------------------------------- Get Unique ID
                   10318:     my $uname;
                   10319:     if ($cnum =~ /^$match_courseid$/) {
                   10320:         my $chome=&homeserver($cnum,$udom,'true');
                   10321:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10322:             $uname = $cnum;
                   10323:         } else {
1.1038    raeburn  10324:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10325:         }
                   10326:     } else {
1.1038    raeburn  10327:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10328:     }
                   10329:     return $uname if ($uname =~ /^error/);
                   10330: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10331:     if (!defined($course_server)) {
                   10332:         if (defined(&domain($udom,'primary'))) {
                   10333:             $course_server = &domain($udom,'primary');
                   10334:         } else {
                   10335:             $course_server = $env{'user.home'}; 
                   10336:         }
                   10337:     }
                   10338:     my %host_servers =
                   10339:         &Apache::lonnet::get_servers($udom,'library');
                   10340:     unless ($host_servers{$course_server}) {
                   10341:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10342:     }
1.84      www      10343: # ------------------------------------------------------------- Make the course
                   10344:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10345:                       $course_server);
1.84      www      10346:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10347:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10348:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10349: 	return 'error: no such course';
                   10350:     }
1.271     www      10351: # ----------------------------------------------------------------- Course made
1.516     raeburn  10352: # log existence
1.1029    raeburn  10353:     my $now = time;
1.918     raeburn  10354:     my $newcourse = {
                   10355:                     $udom.'_'.$uname => {
1.921     raeburn  10356:                                      description => $description,
                   10357:                                      inst_code   => $inst_code,
                   10358:                                      owner       => $course_owner,
                   10359:                                      type        => $crstype,
1.1029    raeburn  10360:                                      creator     => $env{'user.name'}.':'.
                   10361:                                                     $env{'user.domain'},
                   10362:                                      created     => $now,
                   10363:                                      context     => $context,
1.918     raeburn  10364:                                                 },
                   10365:                     };
1.921     raeburn  10366:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10367: # set toplevel url
1.271     www      10368:     my $topurl=$url;
                   10369:     unless ($nonstandard) {
                   10370: # ------------------------------------------ For standard courses, make top url
                   10371:         my $mapurl=&clutter($url);
1.278     www      10372:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10373:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10374: <map>
                   10375: <resource id="1" type="start"></resource>
                   10376: <resource id="2" src="$mapurl"></resource>
                   10377: <resource id="3" type="finish"></resource>
                   10378: <link index="1" from="1" to="2"></link>
                   10379: <link index="2" from="2" to="3"></link>
                   10380: </map>
                   10381: ENDINITMAP
                   10382:         $topurl=&declutter(
1.638     albertel 10383:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10384:                           );
                   10385:     }
                   10386: # ----------------------------------------------------------- Write preferences
1.84      www      10387:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10388:                      ('description'              => $description,
                   10389:                       'url'                      => $topurl,
                   10390:                       'internal.creator'         => $env{'user.name'}.':'.
                   10391:                                                     $env{'user.domain'},
                   10392:                       'internal.created'         => $now,
                   10393:                       'internal.creationcontext' => $context)
                   10394:                     );
1.84      www      10395:     return '/'.$udom.'/'.$uname;
                   10396: }
                   10397: 
1.1011    raeburn  10398: # ------------------------------------------------------------------- Create ID
                   10399: sub generate_coursenum {
1.1038    raeburn  10400:     my ($udom,$crstype) = @_;
1.1011    raeburn  10401:     my $domdesc = &domain($udom);
                   10402:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10403:     my $first;
                   10404:     if ($crstype eq 'Community') {
                   10405:         $first = '0';
                   10406:     } else {
                   10407:         $first = int(1+rand(9)); 
                   10408:     } 
                   10409:     my $uname=$first.
1.1011    raeburn  10410:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10411:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10412:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10413: # ----------------------------------------------- Make sure that does not exist
                   10414:     my $uhome=&homeserver($uname,$udom,'true');
                   10415:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10416:         if ($crstype eq 'Community') {
                   10417:             $first = '0';
                   10418:         } else {
                   10419:             $first = int(1+rand(9));
                   10420:         }
                   10421:         $uname=$first.
1.1011    raeburn  10422:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10423:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10424:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10425:         $uhome=&homeserver($uname,$udom,'true');
                   10426:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10427:             return 'error: unable to generate unique course-ID';
                   10428:         }
                   10429:     }
                   10430:     return $uname;
                   10431: }
                   10432: 
1.813     albertel 10433: sub is_course {
1.1167    droeschl 10434:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10435:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10436:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10437:     my $uhome=&homeserver($cnum,$cdom);
                   10438:     my $iscourse;
                   10439:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10440:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10441:     } else {
                   10442:         my $hashid = $cdom.':'.$cnum;
                   10443:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10444:         unless (defined($cached)) {
                   10445:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10446:                                         $cnum,undef,undef,'.');
                   10447:             $iscourse = 0;
                   10448:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10449:                 $iscourse = 1;
                   10450:             }
                   10451:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10452:         }
                   10453:     }
                   10454:     return unless($iscourse);
1.1167    droeschl 10455:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10456: }
                   10457: 
1.1015    raeburn  10458: sub store_userdata {
                   10459:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10460:     my $result;
1.1016    raeburn  10461:     if ($datakey ne '') {
1.1013    raeburn  10462:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10463:             if ($udom eq '' || $uname eq '') {
                   10464:                 $udom = $env{'user.domain'};
                   10465:                 $uname = $env{'user.name'};
                   10466:             }
                   10467:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10468:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10469:                 $result = 'error: no_host';
                   10470:             } else {
                   10471:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10472:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10473: 
                   10474:                 my $namevalue='';
                   10475:                 foreach my $key (keys(%{$storehash})) {
                   10476:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10477:                 }
                   10478:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10479:                 unless ($namespace eq 'courserequests') {
                   10480:                     $datakey = &escape($datakey);
                   10481:                 }
1.1105    raeburn  10482:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10483:                                   $namevalue,$uhome);
1.1013    raeburn  10484:             }
                   10485:         } else {
                   10486:             $result = 'error: data to store was not a hash reference'; 
                   10487:         }
                   10488:     } else {
                   10489:         $result= 'error: invalid requestkey'; 
                   10490:     }
                   10491:     return $result;
                   10492: }
                   10493: 
1.21      www      10494: # ---------------------------------------------------------- Assign Custom Role
                   10495: 
                   10496: sub assigncustomrole {
1.957     raeburn  10497:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10498:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10499:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10500: }
                   10501: 
                   10502: # ----------------------------------------------------------------- Revoke Role
                   10503: 
                   10504: sub revokerole {
1.957     raeburn  10505:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10506:     my $now=time;
1.965     raeburn  10507:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10508: }
                   10509: 
                   10510: # ---------------------------------------------------------- Revoke Custom Role
                   10511: 
                   10512: sub revokecustomrole {
1.957     raeburn  10513:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10514:     my $now=time;
1.357     www      10515:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10516:            $deleteflag,$selfenroll,$context);
1.17      www      10517: }
                   10518: 
1.533     banghart 10519: # ------------------------------------------------------------ Disk usage
1.535     albertel 10520: sub diskusage {
1.955     raeburn  10521:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10522:     $directorypath =~ s/\/$//;
                   10523:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10524:                        .&escape($getpropath).':'.&escape($uname).':'
                   10525:                        .&escape($udom),homeserver($uname,$udom));
                   10526:     if ($listing eq 'unknown_cmd') {
                   10527:         if ($getpropath) {
                   10528:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10529:         }
                   10530:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10531:     }
1.514     albertel 10532:     return $listing;
1.512     banghart 10533: }
                   10534: 
1.566     banghart 10535: sub is_locked {
1.1096    raeburn  10536:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10537:     my @check;
                   10538:     my $is_locked;
1.1093    raeburn  10539:     push (@check,$file_name);
1.613     albertel 10540:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10541: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10542:     my ($tmp)=keys(%locked);
                   10543:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10544:     
1.566     banghart 10545:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10546:         $is_locked = 'false';
                   10547:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10548:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10549:                $is_locked = 'true';
1.1096    raeburn  10550:                if (ref($which) eq 'ARRAY') {
                   10551:                    push(@{$which},$entry);
                   10552:                } else {
                   10553:                    last;
                   10554:                }
1.745     raeburn  10555:            }
                   10556:        }
1.566     banghart 10557:     } else {
                   10558:         $is_locked = 'false';
                   10559:     }
1.1093    raeburn  10560:     return $is_locked;
1.566     banghart 10561: }
                   10562: 
1.759     albertel 10563: sub declutter_portfile {
                   10564:     my ($file) = @_;
1.833     albertel 10565:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10566:     return $file;
                   10567: }
                   10568: 
1.559     banghart 10569: # ------------------------------------------------------------- Mark as Read Only
                   10570: 
                   10571: sub mark_as_readonly {
                   10572:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10573:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10574:     my ($tmp)=keys(%current_permissions);
                   10575:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10576:     foreach my $file (@{$files}) {
1.759     albertel 10577: 	$file = &declutter_portfile($file);
1.561     banghart 10578:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10579:     }
1.613     albertel 10580:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10581:     return;
                   10582: }
                   10583: 
1.572     banghart 10584: # ------------------------------------------------------------Save Selected Files
                   10585: 
                   10586: sub save_selected_files {
                   10587:     my ($user, $path, @files) = @_;
                   10588:     my $filename = $user."savedfiles";
1.573     banghart 10589:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10590:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10591:     foreach my $file (@files) {
1.620     albertel 10592:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10593:     }
                   10594:     foreach my $file (@other_files) {
1.574     banghart 10595:         print (OUT $file."\n");
1.572     banghart 10596:     }
1.574     banghart 10597:     close (OUT);
1.572     banghart 10598:     return 'ok';
                   10599: }
                   10600: 
1.574     banghart 10601: sub clear_selected_files {
                   10602:     my ($user) = @_;
                   10603:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10604:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10605:     print (OUT undef);
                   10606:     close (OUT);
                   10607:     return ("ok");    
                   10608: }
                   10609: 
1.572     banghart 10610: sub files_in_path {
                   10611:     my ($user, $path) = @_;
                   10612:     my $filename = $user."savedfiles";
                   10613:     my %return_files;
1.1172.2.96  raeburn  10614:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10615:     while (my $line_in = <IN>) {
1.574     banghart 10616:         chomp ($line_in);
                   10617:         my @paths_and_file = split (m!/!, $line_in);
                   10618:         my $file_part = pop (@paths_and_file);
                   10619:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10620:         $path_part.='/';
                   10621:         my $path_and_file = $path_part.$file_part;
                   10622:         if ($path_part eq $path) {
                   10623:             $return_files{$file_part}= 'selected';
                   10624:         }
                   10625:     }
1.574     banghart 10626:     close (IN);
                   10627:     return (\%return_files);
1.572     banghart 10628: }
                   10629: 
                   10630: # called in portfolio select mode, to show files selected NOT in current directory
                   10631: sub files_not_in_path {
                   10632:     my ($user, $path) = @_;
                   10633:     my $filename = $user."savedfiles";
                   10634:     my @return_files;
                   10635:     my $path_part;
1.1172.2.96  raeburn  10636:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10637:     while (my $line = <IN>) {
1.572     banghart 10638:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10639:         my @paths_and_file = split(m|/|, $line);
                   10640:         my $file_part = pop(@paths_and_file);
                   10641:         chomp($file_part);
                   10642:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10643:         $path_part .= '/';
                   10644:         my $path_and_file = $path_part.$file_part;
                   10645:         if ($path_part ne $path) {
1.800     albertel 10646:             push(@return_files, ($path_and_file));
1.572     banghart 10647:         }
                   10648:     }
1.800     albertel 10649:     close(OUT);
1.574     banghart 10650:     return (@return_files);
1.572     banghart 10651: }
                   10652: 
1.745     raeburn  10653: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10654: 
1.745     raeburn  10655: sub get_portfile_permissions {
                   10656:     my ($domain,$user) = @_;
1.613     albertel 10657:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10658:     my ($tmp)=keys(%current_permissions);
                   10659:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10660:     return \%current_permissions;
                   10661: }
                   10662: 
                   10663: #---------------------------------------------Get portfolio file access controls
                   10664: 
1.749     raeburn  10665: sub get_access_controls {
1.745     raeburn  10666:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10667:     my %access;
                   10668:     my $real_file = $file;
                   10669:     $file =~ s/\.meta$//;
1.745     raeburn  10670:     if (defined($file)) {
1.749     raeburn  10671:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10672:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10673:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10674:             }
                   10675:         }
1.745     raeburn  10676:     } else {
1.749     raeburn  10677:         foreach my $key (keys(%{$current_permissions})) {
                   10678:             if ($key =~ /\0accesscontrol$/) {
                   10679:                 if (defined($group)) {
                   10680:                     if ($key !~ m-^\Q$group\E/-) {
                   10681:                         next;
                   10682:                     }
                   10683:                 }
                   10684:                 my ($fullpath) = split(/\0/,$key);
                   10685:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10686:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10687:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10688:                     }
                   10689:                 }
                   10690:             }
                   10691:         }
                   10692:     }
                   10693:     return %access;
                   10694: }
                   10695: 
                   10696: sub modify_access_controls {
                   10697:     my ($file_name,$changes,$domain,$user)=@_;
                   10698:     my ($outcome,$deloutcome);
                   10699:     my %store_permissions;
                   10700:     my %new_values;
                   10701:     my %new_control;
                   10702:     my %translation;
                   10703:     my @deletions = ();
                   10704:     my $now = time;
                   10705:     if (exists($$changes{'activate'})) {
                   10706:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10707:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10708:             my $numnew = scalar(@newitems);
                   10709:             for (my $i=0; $i<$numnew; $i++) {
                   10710:                 my $newkey = $newitems[$i];
                   10711:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10712:                 if ($newkey =~ /^\d+:/) { 
                   10713:                     $newkey =~ s/^(\d+)/$newid/;
                   10714:                     $translation{$1} = $newid;
                   10715:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10716:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10717:                     $translation{$1} = $newid;
                   10718:                 }
1.749     raeburn  10719:                 $new_values{$file_name."\0".$newkey} = 
                   10720:                                           $$changes{'activate'}{$newitems[$i]};
                   10721:                 $new_control{$newkey} = $now;
                   10722:             }
                   10723:         }
                   10724:     }
                   10725:     my %todelete;
                   10726:     my %changed_items;
                   10727:     foreach my $action ('delete','update') {
                   10728:         if (exists($$changes{$action})) {
                   10729:             if (ref($$changes{$action}) eq 'HASH') {
                   10730:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10731:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10732:                     if ($action eq 'delete') { 
                   10733:                         $todelete{$itemnum} = 1;
                   10734:                     } else {
                   10735:                         $changed_items{$itemnum} = $key;
                   10736:                     }
                   10737:                 }
1.745     raeburn  10738:             }
                   10739:         }
1.749     raeburn  10740:     }
                   10741:     # get lock on access controls for file.
                   10742:     my $lockhash = {
                   10743:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10744:                                                        ':'.$env{'user.domain'},
                   10745:                    }; 
                   10746:     my $tries = 0;
                   10747:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10748:    
1.1172.2.79  raeburn  10749:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10750:         $tries ++;
1.1172.2.79  raeburn  10751:         sleep(0.1);
1.749     raeburn  10752:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10753:     }
                   10754:     if ($gotlock eq 'ok') {
                   10755:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10756:         my ($tmp)=keys(%curr_permissions);
                   10757:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10758:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10759:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10760:             if (ref($curr_controls) eq 'HASH') {
                   10761:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10762:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10763:                     if (defined($todelete{$itemnum})) {
                   10764:                         push(@deletions,$file_name."\0".$control_item);
                   10765:                     } else {
                   10766:                         if (defined($changed_items{$itemnum})) {
                   10767:                             $new_control{$changed_items{$itemnum}} = $now;
                   10768:                             push(@deletions,$file_name."\0".$control_item);
                   10769:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10770:                         } else {
                   10771:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10772:                         }
                   10773:                     }
1.745     raeburn  10774:                 }
                   10775:             }
                   10776:         }
1.970     raeburn  10777:         my ($group);
                   10778:         if (&is_course($domain,$user)) {
                   10779:             ($group,my $file) = split(/\//,$file_name,2);
                   10780:         }
1.749     raeburn  10781:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10782:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10783:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10784:         #  remove lock
                   10785:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10786:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10787:         my $sqlresult =
1.970     raeburn  10788:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10789:                                     $group);
1.749     raeburn  10790:     } else {
                   10791:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10792:     }
1.749     raeburn  10793:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10794: }
                   10795: 
1.827     raeburn  10796: sub make_public_indefinitely {
                   10797:     my ($requrl) = @_;
                   10798:     my $now = time;
                   10799:     my $action = 'activate';
                   10800:     my $aclnum = 0;
                   10801:     if (&is_portfolio_url($requrl)) {
                   10802:         my (undef,$udom,$unum,$file_name,$group) =
                   10803:             &parse_portfolio_url($requrl);
                   10804:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10805:         my %access_controls = &get_access_controls($current_perms,
                   10806:                                                    $group,$file_name);
                   10807:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10808:             my ($num,$scope,$end,$start) = 
                   10809:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10810:             if ($scope eq 'public') {
                   10811:                 if ($start <= $now && $end == 0) {
                   10812:                     $action = 'none';
                   10813:                 } else {
                   10814:                     $action = 'update';
                   10815:                     $aclnum = $num;
                   10816:                 }
                   10817:                 last;
                   10818:             }
                   10819:         }
                   10820:         if ($action eq 'none') {
                   10821:              return 'ok';
                   10822:         } else {
                   10823:             my %changes;
                   10824:             my $newend = 0;
                   10825:             my $newstart = $now;
                   10826:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10827:             $changes{$action}{$newkey} = {
                   10828:                 type => 'public',
                   10829:                 time => {
                   10830:                     start => $newstart,
                   10831:                     end   => $newend,
                   10832:                 },
                   10833:             };
                   10834:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10835:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10836:             return $outcome;
                   10837:         }
                   10838:     } else {
                   10839:         return 'invalid';
                   10840:     }
                   10841: }
                   10842: 
1.745     raeburn  10843: #------------------------------------------------------Get Marked as Read Only
                   10844: 
                   10845: sub get_marked_as_readonly {
                   10846:     my ($domain,$user,$what,$group) = @_;
                   10847:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10848:     my @readonly_files;
1.629     banghart 10849:     my $cmp1=$what;
                   10850:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10851:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10852:         if (defined($group)) {
                   10853:             if ($file_name !~ m-^\Q$group\E/-) {
                   10854:                 next;
                   10855:             }
                   10856:         }
1.561     banghart 10857:         if (ref($value) eq "ARRAY"){
                   10858:             foreach my $stored_what (@{$value}) {
1.629     banghart 10859:                 my $cmp2=$stored_what;
1.759     albertel 10860:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10861:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10862:                 }
1.629     banghart 10863:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10864:                     push(@readonly_files, $file_name);
1.745     raeburn  10865:                     last;
1.563     banghart 10866:                 } elsif (!defined($what)) {
                   10867:                     push(@readonly_files, $file_name);
1.745     raeburn  10868:                     last;
1.561     banghart 10869:                 }
                   10870:             }
1.745     raeburn  10871:         }
1.561     banghart 10872:     }
                   10873:     return @readonly_files;
                   10874: }
1.577     banghart 10875: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10876: 
1.577     banghart 10877: sub get_marked_as_readonly_hash {
1.745     raeburn  10878:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10879:     my %readonly_files;
1.745     raeburn  10880:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10881:         if (defined($group)) {
                   10882:             if ($file_name !~ m-^\Q$group\E/-) {
                   10883:                 next;
                   10884:             }
                   10885:         }
1.577     banghart 10886:         if (ref($value) eq "ARRAY"){
                   10887:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10888:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10889:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10890:                         if ($lock_descriptor eq 'graded') {
                   10891:                             $readonly_files{$file_name} = 'graded';
                   10892:                         } elsif ($lock_descriptor eq 'handback') {
                   10893:                             $readonly_files{$file_name} = 'handback';
                   10894:                         } else {
                   10895:                             if (!exists($readonly_files{$file_name})) {
                   10896:                                 $readonly_files{$file_name} = 'locked';
                   10897:                             }
                   10898:                         }
1.745     raeburn  10899:                     }
1.750     banghart 10900:                 } 
1.577     banghart 10901:             }
                   10902:         } 
                   10903:     }
                   10904:     return %readonly_files;
                   10905: }
1.559     banghart 10906: # ------------------------------------------------------------ Unmark as Read Only
                   10907: 
                   10908: sub unmark_as_readonly {
1.629     banghart 10909:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10910:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10911:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10912:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10913:     my $symb_crs = $what;
                   10914:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10915:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10916:     my ($tmp)=keys(%current_permissions);
                   10917:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10918:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10919:     foreach my $file (@readonly_files) {
1.759     albertel 10920: 	my $clean_file = &declutter_portfile($file);
                   10921: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10922: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10923:         my @new_locks;
                   10924:         my @del_keys;
                   10925:         if (ref($current_locks) eq "ARRAY"){
                   10926:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10927:                 my $compare=$locker;
1.749     raeburn  10928:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10929:                     $compare=join('',@{$locker});
1.746     raeburn  10930:                     if ($compare ne $symb_crs) {
                   10931:                         push(@new_locks, $locker);
                   10932:                     }
1.563     banghart 10933:                 }
                   10934:             }
1.650     albertel 10935:             if (scalar(@new_locks) > 0) {
1.563     banghart 10936:                 $current_permissions{$file} = \@new_locks;
                   10937:             } else {
                   10938:                 push(@del_keys, $file);
1.613     albertel 10939:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10940:                 delete($current_permissions{$file});
1.563     banghart 10941:             }
                   10942:         }
1.561     banghart 10943:     }
1.613     albertel 10944:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10945:     return;
                   10946: }
1.512     banghart 10947: 
1.17      www      10948: # ------------------------------------------------------------ Directory lister
                   10949: 
                   10950: sub dirlist {
1.955     raeburn  10951:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10952:     $uri=~s/^\///;
                   10953:     $uri=~s/\/$//;
1.253     stredwic 10954:     my ($udom, $uname);
1.955     raeburn  10955:     if ($getuserdir) {
1.253     stredwic 10956:         $udom = $userdomain;
                   10957:         $uname = $username;
1.955     raeburn  10958:     } else {
                   10959:         (undef,$udom,$uname)=split(/\//,$uri);
                   10960:         if(defined($userdomain)) {
                   10961:             $udom = $userdomain;
                   10962:         }
                   10963:         if(defined($username)) {
                   10964:             $uname = $username;
                   10965:         }
1.253     stredwic 10966:     }
1.955     raeburn  10967:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10968: 
1.955     raeburn  10969:     $dirRoot = $perlvar{'lonDocRoot'};
                   10970:     if (defined($getpropath)) {
                   10971:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10972:         $dirRoot =~ s/\/$//;
1.955     raeburn  10973:     } elsif (defined($getuserdir)) {
                   10974:         my $subdir=$uname.'__';
                   10975:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10976:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10977:                    ."/$udom/$subdir/$uname";
                   10978:     } elsif (defined($alternateRoot)) {
                   10979:         $dirRoot = $alternateRoot;
1.751     banghart 10980:     }
1.253     stredwic 10981: 
                   10982:     if($udom) {
                   10983:         if($uname) {
1.1135    raeburn  10984:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10985:             if ($uhome eq 'no_host') {
                   10986:                 return ([],'no_host');
                   10987:             }
1.955     raeburn  10988:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10989:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10990:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10991:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10992:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10993:             } else {
                   10994:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10995:             }
1.605     matthew  10996:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10997:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10998:                 @listing_results = split(/:/,$listing);
                   10999:             } else {
                   11000:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11001:             }
1.1135    raeburn  11002:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11003:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11004:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11005:                 return ([],$listing);
                   11006:             } else {
                   11007:                 return (\@listing_results);
1.1135    raeburn  11008:             }
1.955     raeburn  11009:         } elsif(!$alternateRoot) {
1.1136    raeburn  11010:             my (%allusers,%listerror);
1.841     albertel 11011: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11012:  	    foreach my $tryserver (keys(%servers)) {
                   11013:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11014:                                   &escape($udom),$tryserver);
                   11015:                 if ($listing eq 'unknown_cmd') {
                   11016: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11017: 				      $udom, $tryserver);
                   11018:                 } else {
                   11019:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11020:                 }
1.841     albertel 11021: 		if ($listing eq 'unknown_cmd') {
                   11022: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11023: 				      $udom, $tryserver);
                   11024: 		    @listing_results = split(/:/,$listing);
                   11025: 		} else {
                   11026: 		    @listing_results =
                   11027: 			map { &unescape($_); } split(/:/,$listing);
                   11028: 		}
1.1136    raeburn  11029:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11030:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11031:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11032:                     $listerror{$tryserver} = $listing;
                   11033:                 } else {
1.841     albertel 11034: 		    foreach my $line (@listing_results) {
                   11035: 			my ($entry) = split(/&/,$line,2);
                   11036: 			$allusers{$entry} = 1;
                   11037: 		    }
                   11038: 		}
1.253     stredwic 11039:             }
1.1136    raeburn  11040:             my @alluserslist=();
1.800     albertel 11041:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11042:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11043:             }
1.1172.2.80  raeburn  11044:             if (!%listerror) {
                   11045:                 # no errors
                   11046:                 return (\@alluserslist);
                   11047:             } elsif (scalar(keys(%servers)) == 1) {
                   11048:                 # one library server, one error
                   11049:                 my ($key) = keys(%listerror);
                   11050:                 return (\@alluserslist, $listerror{$key});
                   11051:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11052:                 # con_lost indicates that we might miss data from at least one
                   11053:                 # library server
                   11054:                 return (\@alluserslist, 'con_lost');
                   11055:             } else {
                   11056:                 # multiple library servers and no con_lost -> data should be
                   11057:                 # complete.
                   11058:                 return (\@alluserslist);
                   11059:             }
                   11060: 
1.253     stredwic 11061:         } else {
1.1136    raeburn  11062:             return ([],'missing username');
1.253     stredwic 11063:         }
1.955     raeburn  11064:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11065:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11066:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11067:         return (\@all_domains);
1.955     raeburn  11068:     } else {
1.1136    raeburn  11069:         return ([],'missing domain');
1.275     stredwic 11070:     }
                   11071: }
                   11072: 
                   11073: # --------------------------------------------- GetFileTimestamp
                   11074: # This function utilizes dirlist and returns the date stamp for
                   11075: # when it was last modified.  It will also return an error of -1
                   11076: # if an error occurs
                   11077: 
                   11078: sub GetFileTimestamp {
1.955     raeburn  11079:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11080:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11081:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11082:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11083:                                     undef,$getuserdir);
                   11084:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11085:         return -1;
                   11086:     }
                   11087:     if (ref($fileref) eq 'ARRAY') {
                   11088:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11089:         # @stats contains first the filename, then the stat output
                   11090:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11091:     } else {
                   11092:         return -1;
1.253     stredwic 11093:     }
1.26      www      11094: }
                   11095: 
1.712     albertel 11096: sub stat_file {
                   11097:     my ($uri) = @_;
1.787     albertel 11098:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11099: 
1.955     raeburn  11100:     my ($udom,$uname,$file);
1.712     albertel 11101:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11102: 	($udom,$uname,$file) =
1.811     albertel 11103: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11104: 	$file = 'userfiles/'.$file;
                   11105:     }
                   11106:     if ($uri =~ m-^/res/-) {
                   11107: 	($udom,$uname) = 
1.807     albertel 11108: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11109: 	$file = $uri;
                   11110:     }
                   11111: 
                   11112:     if (!$udom || !$uname || !$file) {
                   11113: 	# unable to handle the uri
                   11114: 	return ();
                   11115:     }
1.956     raeburn  11116:     my $getpropath;
                   11117:     if ($file =~ /^userfiles\//) {
                   11118:         $getpropath = 1;
                   11119:     }
1.1136    raeburn  11120:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11121:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11122:         return ();
                   11123:     } else {
                   11124:         if (ref($listref) eq 'ARRAY') {
                   11125:             my @stats = split('&',$listref->[0]);
                   11126: 	    shift(@stats); #filename is first
                   11127: 	    return @stats;
                   11128:         }
1.712     albertel 11129:     }
                   11130:     return ();
                   11131: }
                   11132: 
1.26      www      11133: # -------------------------------------------------------- Value of a Condition
                   11134: 
1.713     albertel 11135: # gets the value of a specific preevaluated condition
                   11136: #    stored in the string  $env{user.state.<cid>}
                   11137: # or looks up a condition reference in the bighash and if if hasn't
                   11138: # already been evaluated recurses into docondval to get the value of
                   11139: # the condition, then memoizing it to 
                   11140: #   $env{user.state.<cid>.<condition>}
1.40      www      11141: sub directcondval {
                   11142:     my $number=shift;
1.620     albertel 11143:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11144: 	&Apache::lonuserstate::evalstate();
                   11145:     }
1.713     albertel 11146:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11147: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11148:     } elsif ($number =~ /^_/) {
                   11149: 	my $sub_condition;
                   11150: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11151: 		&GDBM_READER(),0640)) {
                   11152: 	    $sub_condition=$bighash{'conditions'.$number};
                   11153: 	    untie(%bighash);
                   11154: 	}
                   11155: 	my $value = &docondval($sub_condition);
1.949     raeburn  11156: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11157: 	return $value;
                   11158:     }
1.620     albertel 11159:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11160:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11161:     } else {
                   11162:        return 2;
                   11163:     }
                   11164: }
                   11165: 
1.713     albertel 11166: # get the collection of conditions for this resource
1.26      www      11167: sub condval {
                   11168:     my $condidx=shift;
1.54      www      11169:     my $allpathcond='';
1.713     albertel 11170:     foreach my $cond (split(/\|/,$condidx)) {
                   11171: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11172: 	    $allpathcond.=
                   11173: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11174: 	}
1.191     harris41 11175:     }
1.54      www      11176:     $allpathcond=~s/\|$//;
1.713     albertel 11177:     return &docondval($allpathcond);
                   11178: }
                   11179: 
                   11180: #evaluates an expression of conditions
                   11181: sub docondval {
                   11182:     my ($allpathcond) = @_;
                   11183:     my $result=0;
                   11184:     if ($env{'request.course.id'}
                   11185: 	&& defined($allpathcond)) {
                   11186: 	my $operand='|';
                   11187: 	my @stack;
                   11188: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11189: 	    if ($chunk eq '(') {
                   11190: 		push @stack,($operand,$result);
                   11191: 	    } elsif ($chunk eq ')') {
                   11192: 		my $before=pop @stack;
                   11193: 		if (pop @stack eq '&') {
                   11194: 		    $result=$result>$before?$before:$result;
                   11195: 		} else {
                   11196: 		    $result=$result>$before?$result:$before;
                   11197: 		}
                   11198: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11199: 		$operand=$chunk;
                   11200: 	    } else {
                   11201: 		my $new=directcondval($chunk);
                   11202: 		if ($operand eq '&') {
                   11203: 		    $result=$result>$new?$new:$result;
                   11204: 		} else {
                   11205: 		    $result=$result>$new?$result:$new;
                   11206: 		}
                   11207: 	    }
                   11208: 	}
1.26      www      11209:     }
                   11210:     return $result;
1.421     albertel 11211: }
                   11212: 
                   11213: # ---------------------------------------------------- Devalidate courseresdata
                   11214: 
                   11215: sub devalidatecourseresdata {
                   11216:     my ($coursenum,$coursedomain)=@_;
                   11217:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11218:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11219: }
                   11220: 
1.763     www      11221: 
1.200     www      11222: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11223: #
                   11224: #  Parameters:
                   11225: #      $coursenum    - Number of the course.
                   11226: #      $coursedomain - Domain at which the course was created.
                   11227: #  Returns:
                   11228: #     A hash of the course parameters along (I think) with timestamps
                   11229: #     and version info.
1.877     foxr     11230: 
1.624     albertel 11231: sub get_courseresdata {
                   11232:     my ($coursenum,$coursedomain)=@_;
1.200     www      11233:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11234:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11235:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11236:     my %dumpreply;
1.417     albertel 11237:     unless (defined($cached)) {
1.624     albertel 11238: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11239: 	$result=\%dumpreply;
1.251     albertel 11240: 	my ($tmp) = keys(%dumpreply);
                   11241: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11242: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11243: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11244: 	    return $tmp;
1.416     albertel 11245: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11246: 	    $result=undef;
1.599     albertel 11247: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11248: 	}
                   11249:     }
1.624     albertel 11250:     return $result;
                   11251: }
                   11252: 
1.633     albertel 11253: sub devalidateuserresdata {
                   11254:     my ($uname,$udom)=@_;
                   11255:     my $hashid="$udom:$uname";
                   11256:     &devalidate_cache_new('userres',$hashid);
                   11257: }
                   11258: 
1.624     albertel 11259: sub get_userresdata {
                   11260:     my ($uname,$udom)=@_;
                   11261:     #most student don\'t have any data set, check if there is some data
                   11262:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11263: 
                   11264:     my $hashid="$udom:$uname";
                   11265:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11266:     if (!defined($cached)) {
                   11267: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11268: 	$result=\%resourcedata;
                   11269: 	&do_cache_new('userres',$hashid,$result,600);
                   11270:     }
                   11271:     my ($tmp)=keys(%$result);
                   11272:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11273: 	return $result;
                   11274:     }
                   11275:     #error 2 occurs when the .db doesn't exist
                   11276:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11277:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11278: 	    &logthis("<font color=\"blue\">WARNING:".
                   11279: 		     " Trying to get resource data for ".
                   11280: 		     $uname." at ".$udom.": ".
                   11281: 		     $tmp."</font>");
                   11282:         }
1.624     albertel 11283:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11284: 	#&EXT_cache_set($udom,$uname);
                   11285: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11286: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11287:     }
                   11288:     return $tmp;
                   11289: }
1.879     foxr     11290: #----------------------------------------------- resdata - return resource data
                   11291: #  Purpose:
                   11292: #    Return resource data for either users or for a course.
                   11293: #  Parameters:
                   11294: #     $name      - Course/user name.
                   11295: #     $domain    - Name of the domain the user/course is registered on.
                   11296: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11297: #     @which     - Array of names of resources desired.
                   11298: #  Returns:
                   11299: #     The value of the first reasource in @which that is found in the
                   11300: #     resource hash.
                   11301: #  Exceptional Conditions:
                   11302: #     If the $type passed in is not valid (not the string 'course' or 
                   11303: #     'user', an undefined  reference is returned.
                   11304: #     If none of the resources are found, an undef is returned
1.624     albertel 11305: sub resdata {
                   11306:     my ($name,$domain,$type,@which)=@_;
                   11307:     my $result;
                   11308:     if ($type eq 'course') {
                   11309: 	$result=&get_courseresdata($name,$domain);
                   11310:     } elsif ($type eq 'user') {
                   11311: 	$result=&get_userresdata($name,$domain);
                   11312:     }
                   11313:     if (!ref($result)) { return $result; }    
1.251     albertel 11314:     foreach my $item (@which) {
1.927     albertel 11315: 	if (defined($result->{$item->[0]})) {
                   11316: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11317: 	}
1.250     albertel 11318:     }
1.291     albertel 11319:     return undef;
1.200     www      11320: }
                   11321: 
1.1172.2.31  raeburn  11322: sub get_numsuppfiles {
                   11323:     my ($cnum,$cdom,$ignorecache)=@_;
                   11324:     my $hashid=$cnum.':'.$cdom;
                   11325:     my ($suppcount,$cached);
                   11326:     unless ($ignorecache) {
                   11327:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11328:     }
                   11329:     unless (defined($cached)) {
                   11330:         my $chome=&homeserver($cnum,$cdom);
                   11331:         unless ($chome eq 'no_host') {
                   11332:             ($suppcount,my $errors) = (0,0);
                   11333:             my $suppmap = 'supplemental.sequence';
                   11334:             ($suppcount,$errors) =
                   11335:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11336:         }
                   11337:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11338:     }
                   11339:     return $suppcount;
                   11340: }
                   11341: 
1.379     matthew  11342: #
                   11343: # EXT resource caching routines
                   11344: #
                   11345: 
                   11346: sub clear_EXT_cache_status {
1.383     albertel 11347:     &delenv('cache.EXT.');
1.379     matthew  11348: }
                   11349: 
                   11350: sub EXT_cache_status {
                   11351:     my ($target_domain,$target_user) = @_;
1.383     albertel 11352:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11353:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11354:         # We know already the user has no data
                   11355:         return 1;
                   11356:     } else {
                   11357:         return 0;
                   11358:     }
                   11359: }
                   11360: 
                   11361: sub EXT_cache_set {
                   11362:     my ($target_domain,$target_user) = @_;
1.383     albertel 11363:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11364:     #&appenv({$cachename => time});
1.379     matthew  11365: }
                   11366: 
1.28      www      11367: # --------------------------------------------------------- Value of a Variable
1.58      www      11368: sub EXT {
1.715     albertel 11369: 
1.1172.2.28  raeburn  11370:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11371:     unless ($varname) { return ''; }
1.218     albertel 11372:     #get real user name/domain, courseid and symb
                   11373:     my $courseid;
1.359     albertel 11374:     my $publicuser;
1.427     www      11375:     if ($symbparm) {
                   11376: 	$symbparm=&get_symb_from_alias($symbparm);
                   11377:     }
1.218     albertel 11378:     if (!($uname && $udom)) {
1.790     albertel 11379:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11380:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11381:     } else {
1.620     albertel 11382: 	$courseid=$env{'request.course.id'};
1.218     albertel 11383:     }
1.48      www      11384:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11385:     my $rest;
1.320     albertel 11386:     if (defined($therest[0])) {
1.48      www      11387:        $rest=join('.',@therest);
                   11388:     } else {
                   11389:        $rest='';
                   11390:     }
1.320     albertel 11391: 
1.57      www      11392:     my $qualifierrest=$qualifier;
                   11393:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11394:     my $spacequalifierrest=$space;
                   11395:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11396:     if ($realm eq 'user') {
1.48      www      11397: # --------------------------------------------------------------- user.resource
                   11398: 	if ($space eq 'resource') {
1.651     albertel 11399: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11400: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11401: 		 &&
1.744     albertel 11402: 		 ($symbparm eq &symbread()) ) {	
                   11403: 		# if we are in the middle of processing the resource the
                   11404: 		# get the value we are planning on committing
                   11405:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11406:                     return $Apache::lonhomework::results{$qualifierrest};
                   11407:                 } else {
                   11408:                     return $Apache::lonhomework::history{$qualifierrest};
                   11409:                 }
1.335     albertel 11410: 	    } else {
1.359     albertel 11411: 		my %restored;
1.620     albertel 11412: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11413: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11414: 		} else {
                   11415: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11416: 		}
1.335     albertel 11417: 		return $restored{$qualifierrest};
                   11418: 	    }
1.48      www      11419: # ----------------------------------------------------------------- user.access
                   11420:         } elsif ($space eq 'access') {
1.218     albertel 11421: 	    # FIXME - not supporting calls for a specific user
1.48      www      11422:             return &allowed($qualifier,$rest);
                   11423: # ------------------------------------------ user.preferences, user.environment
                   11424:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11425: 	    if (($uname eq $env{'user.name'}) &&
                   11426: 		($udom eq $env{'user.domain'})) {
                   11427: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11428: 	    } else {
1.359     albertel 11429: 		my %returnhash;
                   11430: 		if (!$publicuser) {
                   11431: 		    %returnhash=&userenvironment($udom,$uname,
                   11432: 						 $qualifierrest);
                   11433: 		}
1.218     albertel 11434: 		return $returnhash{$qualifierrest};
                   11435: 	    }
1.48      www      11436: # ----------------------------------------------------------------- user.course
                   11437:         } elsif ($space eq 'course') {
1.218     albertel 11438: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11439:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11440: # ------------------------------------------------------------------- user.role
                   11441:         } elsif ($space eq 'role') {
1.218     albertel 11442: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11443:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11444:             if ($qualifier eq 'value') {
                   11445: 		return $role;
                   11446:             } elsif ($qualifier eq 'extent') {
                   11447:                 return $where;
                   11448:             }
                   11449: # ----------------------------------------------------------------- user.domain
                   11450:         } elsif ($space eq 'domain') {
1.218     albertel 11451:             return $udom;
1.48      www      11452: # ------------------------------------------------------------------- user.name
                   11453:         } elsif ($space eq 'name') {
1.218     albertel 11454:             return $uname;
1.48      www      11455: # ---------------------------------------------------- Any other user namespace
1.29      www      11456:         } else {
1.359     albertel 11457: 	    my %reply;
                   11458: 	    if (!$publicuser) {
                   11459: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11460: 	    }
                   11461: 	    return $reply{$qualifierrest};
1.48      www      11462:         }
1.236     www      11463:     } elsif ($realm eq 'query') {
                   11464: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11465:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11466: 						[$spacequalifierrest]);
1.620     albertel 11467: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11468:    } elsif ($realm eq 'request') {
1.48      www      11469: # ------------------------------------------------------------- request.browser
                   11470:         if ($space eq 'browser') {
1.1145    bisitz   11471:             return $env{'browser.'.$qualifier};
1.57      www      11472: # ------------------------------------------------------------ request.filename
                   11473:         } else {
1.620     albertel 11474:             return $env{'request.'.$spacequalifierrest};
1.29      www      11475:         }
1.28      www      11476:     } elsif ($realm eq 'course') {
1.48      www      11477: # ---------------------------------------------------------- course.description
1.620     albertel 11478:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11479:     } elsif ($realm eq 'resource') {
1.165     www      11480: 
1.620     albertel 11481: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11482: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11483: 	}
1.693     albertel 11484: 
1.1172.2.30  raeburn  11485:         if ($qualifier eq '') {
                   11486: 	    if ($space eq 'title') {
                   11487: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11488: 	        return &gettitle($symbparm);
                   11489: 	    }
1.693     albertel 11490: 	
1.1172.2.30  raeburn  11491: 	    if ($space eq 'map') {
                   11492: 	        my ($map) = &decode_symb($symbparm);
                   11493: 	        return &symbread($map);
                   11494: 	    }
                   11495:             if ($space eq 'maptitle') {
                   11496:                 my ($map) = &decode_symb($symbparm);
                   11497:                 return &gettitle($map);
                   11498:             }
                   11499: 	    if ($space eq 'filename') {
                   11500: 	        if ($symbparm) {
                   11501: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11502: 	        }
                   11503: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11504: 	    }
1.1172.2.30  raeburn  11505: 
                   11506:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11507:                 if ($space eq 'visibleparts') {
                   11508:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11509:                     my $item;
                   11510:                     if (ref($navmap)) {
                   11511:                         my $res = $navmap->getBySymb($symbparm);
                   11512:                         my $parts = $res->parts();
                   11513:                         if (ref($parts) eq 'ARRAY') {
                   11514:                             $item = join(',',@{$parts});
                   11515:                         }
                   11516:                         undef($navmap);
                   11517:                     }
                   11518:                     return $item;
                   11519:                 }
                   11520:             }
                   11521:         }
1.693     albertel 11522: 
                   11523: 	my ($section, $group, @groups);
1.593     albertel 11524: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11525:         if (($courseid eq '') && ($cid)) {
                   11526:             $courseid = $cid;
                   11527:         }
                   11528: 	if (($symbparm && $courseid) && 
                   11529: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11530: 
1.218     albertel 11531: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11532: 
1.60      www      11533: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11534: 	    my $symbp=$symbparm;
1.735     albertel 11535: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11536: 
                   11537: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11538: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11539: 
1.620     albertel 11540: 	    if (($env{'user.name'} eq $uname) &&
                   11541: 		($env{'user.domain'} eq $udom)) {
                   11542: 		$section=$env{'request.course.sec'};
1.733     raeburn  11543:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11544:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11545: 	    } else {
1.539     albertel 11546: 		if (! defined($usection)) {
1.551     albertel 11547: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11548: 		} else {
                   11549: 		    $section = $usection;
                   11550: 		}
1.733     raeburn  11551:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11552: 	    }
                   11553: 
                   11554: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11555: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11556: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11557: 
1.593     albertel 11558: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11559: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11560: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11561: 
1.60      www      11562: # ----------------------------------------------------------- first, check user
1.624     albertel 11563: 
                   11564: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11565: 				       ([$courselevelr,'resource'],
                   11566: 					[$courselevelm,'map'     ],
                   11567: 					[$courselevel, 'course'  ]));
1.931     albertel 11568: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11569: 
1.594     albertel 11570: # ------------------------------------------------ second, check some of course
1.684     raeburn  11571:             my $coursereply;
1.691     raeburn  11572:             if (@groups > 0) {
                   11573:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11574:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11575:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11576:             }
1.96      www      11577: 
1.684     raeburn  11578: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11579: 				  $env{'course.'.$courseid.'.domain'},
                   11580: 				  'course',
                   11581: 				  ([$seclevelr,   'resource'],
                   11582: 				   [$seclevelm,   'map'     ],
                   11583: 				   [$seclevel,    'course'  ],
                   11584: 				   [$courselevelr,'resource']));
                   11585: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11586: 
1.60      www      11587: # ------------------------------------------------------ third, check map parms
1.218     albertel 11588: 	    my %parmhash=();
                   11589: 	    my $thisparm='';
                   11590: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11591: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11592: 		    &GDBM_READER(),0640)) {
1.218     albertel 11593: 		$thisparm=$parmhash{$symbparm};
                   11594: 		untie(%parmhash);
                   11595: 	    }
1.927     albertel 11596: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11597: 	}
1.594     albertel 11598: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11599: 
1.218     albertel 11600: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11601: 	my $filename;
                   11602: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11603: 	if ($symbparm) {
1.409     www      11604: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11605: 	} else {
1.620     albertel 11606: 	    $filename=$env{'request.filename'};
1.282     albertel 11607: 	}
                   11608: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11609: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11610: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11611: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11612: 
1.927     albertel 11613: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11614: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11615: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11616: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11617: 				     $env{'course.'.$courseid.'.domain'},
                   11618: 				     'course',
1.927     albertel 11619: 				     ([$courselevelm,'map'   ],
                   11620: 				      [$courselevel, 'course']));
                   11621: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11622: 	}
1.145     www      11623: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11624: 	unless ($space eq '0') {
1.336     albertel 11625: 	    my @parts=split(/_/,$space);
                   11626: 	    my $id=pop(@parts);
                   11627: 	    my $part=join('_',@parts);
                   11628: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11629: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11630: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11631: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11632: 	}
1.395     albertel 11633: 	if ($recurse) { return undef; }
                   11634: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11635: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11636: # ---------------------------------------------------- Any other user namespace
                   11637:     } elsif ($realm eq 'environment') {
                   11638: # ----------------------------------------------------------------- environment
1.620     albertel 11639: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11640: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11641: 	} else {
1.770     albertel 11642: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11643: 		return '';
                   11644: 	    }
1.219     albertel 11645: 	    my %returnhash=&userenvironment($udom,$uname,
                   11646: 					    $spacequalifierrest);
                   11647: 	    return $returnhash{$spacequalifierrest};
                   11648: 	}
1.28      www      11649:     } elsif ($realm eq 'system') {
1.48      www      11650: # ----------------------------------------------------------------- system.time
                   11651: 	if ($space eq 'time') {
                   11652: 	    return time;
                   11653:         }
1.696     albertel 11654:     } elsif ($realm eq 'server') {
                   11655: # ----------------------------------------------------------------- system.time
                   11656: 	if ($space eq 'name') {
                   11657: 	    return $ENV{'SERVER_NAME'};
                   11658:         }
1.28      www      11659:     }
1.48      www      11660:     return '';
1.61      www      11661: }
                   11662: 
1.927     albertel 11663: sub get_reply {
                   11664:     my ($reply_value) = @_;
1.940     raeburn  11665:     if (ref($reply_value) eq 'ARRAY') {
                   11666:         if (wantarray) {
                   11667: 	    return @$reply_value;
                   11668:         }
                   11669:         return $reply_value->[0];
                   11670:     } else {
                   11671:         return $reply_value;
1.927     albertel 11672:     }
                   11673: }
                   11674: 
1.691     raeburn  11675: sub check_group_parms {
                   11676:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11677:     my @groupitems = ();
                   11678:     my $resultitem;
1.927     albertel 11679:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11680:     foreach my $group (@{$groups}) {
                   11681:         foreach my $level (@levels) {
1.927     albertel 11682:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11683:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11684:         }
                   11685:     }
                   11686:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11687:                             $env{'course.'.$courseid.'.domain'},
                   11688:                                      'course',@groupitems);
                   11689:     return $coursereply;
                   11690: }
                   11691: 
                   11692: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11693:     my ($courseid,@groups) = @_;
                   11694:     @groups = sort(@groups);
1.691     raeburn  11695:     return @groups;
                   11696: }
                   11697: 
1.395     albertel 11698: sub packages_tab_default {
                   11699:     my ($uri,$varname)=@_;
                   11700:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11701: 
                   11702:     my (@extension,@specifics,$do_default);
                   11703:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11704: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11705: 	if ($pack_type eq 'default') {
                   11706: 	    $do_default=1;
                   11707: 	} elsif ($pack_type eq 'extension') {
                   11708: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11709: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11710: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11711: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11712: 	}
                   11713:     }
                   11714:     # first look for a package that matches the requested part id
                   11715:     foreach my $package (@specifics) {
                   11716: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11717: 	next if ($pack_part ne $part);
                   11718: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11719: 	    return $packagetab{"$pack_type&$name&default"};
                   11720: 	}
                   11721:     }
                   11722:     # look for any possible matching non extension_ package
                   11723:     foreach my $package (@specifics) {
                   11724: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11725: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11726: 	    return $packagetab{"$pack_type&$name&default"};
                   11727: 	}
1.585     albertel 11728: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11729: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11730: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11731: 	}
                   11732:     }
1.738     albertel 11733:     # look for any posible extension_ match
                   11734:     foreach my $package (@extension) {
                   11735: 	my ($package,$pack_type)=@{$package};
                   11736: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11737: 	    return $packagetab{"$pack_type&$name&default"};
                   11738: 	}
                   11739: 	if (defined($packagetab{$package."&$name&default"})) {
                   11740: 	    return $packagetab{$package."&$name&default"};
                   11741: 	}
                   11742:     }
                   11743:     # look for a global default setting
                   11744:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11745: 	return $packagetab{"default&$name&default"};
                   11746:     }
1.395     albertel 11747:     return undef;
                   11748: }
                   11749: 
1.334     albertel 11750: sub add_prefix_and_part {
                   11751:     my ($prefix,$part)=@_;
                   11752:     my $keyroot;
                   11753:     if (defined($prefix) && $prefix !~ /^__/) {
                   11754: 	# prefix that has a part already
                   11755: 	$keyroot=$prefix;
                   11756:     } elsif (defined($prefix)) {
                   11757: 	# prefix that is missing a part
                   11758: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11759:     } else {
                   11760: 	# no prefix at all
                   11761: 	if (defined($part)) { $keyroot='_'.$part; }
                   11762:     }
                   11763:     return $keyroot;
                   11764: }
                   11765: 
1.71      www      11766: # ---------------------------------------------------------------- Get metadata
                   11767: 
1.599     albertel 11768: my %metaentry;
1.1070    www      11769: my %importedpartids;
1.1172.2.99  raeburn  11770: my %importedrespids;
1.71      www      11771: sub metadata {
1.176     www      11772:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11773:     $uri=&declutter($uri);
1.288     albertel 11774:     # if it is a non metadata possible uri return quickly
1.529     albertel 11775:     if (($uri eq '') || 
                   11776: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11777: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11778:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11779: 	return undef;
                   11780:     }
1.1172.2.49  raeburn  11781:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11782: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11783: 	return undef;
1.288     albertel 11784:     }
1.73      www      11785:     my $filename=$uri;
                   11786:     $uri=~s/\.meta$//;
1.172     www      11787: #
                   11788: # Is the metadata already cached?
1.177     www      11789: # Look at timestamp of caching
1.172     www      11790: # Everything is cached by the main uri, libraries are never directly cached
                   11791: #
1.428     albertel 11792:     if (!defined($liburi)) {
1.599     albertel 11793: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11794: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11795:     }
                   11796:     {
1.1069    www      11797: # Imported parts would go here
1.1172.2.99  raeburn  11798:         my @origfiletagids=();
1.1069    www      11799:         my $importedparts=0;
1.1172.2.99  raeburn  11800: 
                   11801: # Imported responseids would go here
                   11802:         my $importedresponses=0;
1.172     www      11803: #
                   11804: # Is this a recursive call for a library?
                   11805: #
1.599     albertel 11806: #	if (! exists($metacache{$uri})) {
                   11807: #	    $metacache{$uri}={};
                   11808: #	}
1.924     albertel 11809: 	my $cachetime = 60*60;
1.171     www      11810:         if ($liburi) {
                   11811: 	    $liburi=&declutter($liburi);
                   11812:             $filename=$liburi;
1.401     bowersj2 11813:         } else {
1.599     albertel 11814: 	    &devalidate_cache_new('meta',$uri);
                   11815: 	    undef(%metaentry);
1.401     bowersj2 11816: 	}
1.140     www      11817:         my %metathesekeys=();
1.73      www      11818:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11819: 	my $metastring;
1.1140    www      11820: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11821: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11822: 	    $metastring = 
1.929     albertel 11823: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11824: 					  ('grade_target' => 'meta'));
                   11825: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11826: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11827:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11828: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11829: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11830: 	    $metastring=&getfile($file);
1.489     albertel 11831: 	}
1.208     albertel 11832:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11833:         my $token;
1.140     www      11834:         undef %metathesekeys;
1.71      www      11835:         while ($token=$parser->get_token) {
1.339     albertel 11836: 	    if ($token->[0] eq 'S') {
                   11837: 		if (defined($token->[2]->{'package'})) {
1.172     www      11838: #
                   11839: # This is a package - get package info
                   11840: #
1.339     albertel 11841: 		    my $package=$token->[2]->{'package'};
                   11842: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11843: 		    if (defined($token->[2]->{'id'})) { 
                   11844: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11845: 		    }
1.599     albertel 11846: 		    if ($metaentry{':packages'}) {
                   11847: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11848: 		    } else {
1.599     albertel 11849: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11850: 		    }
1.736     albertel 11851: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11852: 			my $part=$keyroot;
                   11853: 			$part=~s/^\_//;
1.736     albertel 11854: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11855: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11856: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11857: 			    # ignore package.tab specified default values
                   11858:                             # here &package_tab_default() will fetch those
                   11859: 			    if ($subp eq 'default') { next; }
1.736     albertel 11860: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11861: 			    my $unikey;
                   11862: 			    if ($pack =~ /_0$/) {
                   11863: 				$unikey='parameter_0_'.$name;
                   11864: 				$part=0;
                   11865: 			    } else {
                   11866: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11867: 			    }
1.339     albertel 11868: 			    if ($subp eq 'display') {
                   11869: 				$value.=' [Part: '.$part.']';
                   11870: 			    }
1.599     albertel 11871: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11872: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11873: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11874: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11875: 			    }
1.599     albertel 11876: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11877: 				$metaentry{':'.$unikey}=
                   11878: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11879: 			    }
1.339     albertel 11880: 			}
                   11881: 		    }
                   11882: 		} else {
1.172     www      11883: #
                   11884: # This is not a package - some other kind of start tag
1.339     albertel 11885: #
                   11886: 		    my $entry=$token->[1];
1.1068    www      11887: 		    my $unikey='';
1.175     www      11888: 
1.339     albertel 11889: 		    if ($entry eq 'import') {
1.175     www      11890: #
                   11891: # Importing a library here
1.339     albertel 11892: #
1.1067    www      11893:                         my $location=$parser->get_text('/import');
                   11894:                         my $dir=$filename;
                   11895:                         $dir=~s|[^/]*$||;
                   11896:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11897: 
                   11898:                         my $importid=$token->[2]->{'id'};
1.1068    www      11899:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11900: #
                   11901: # Check metadata for imported file to
                   11902: # see if it contained response items
                   11903: #
                   11904:                         my %currmetaentry = %metaentry;
                   11905:                         my $libresponseorder = &metadata($location,'responseorder');
                   11906:                         my $origfile;
                   11907:                         if ($libresponseorder ne '') {
                   11908:                             if ($#origfiletagids<0) {
                   11909:                                 undef(%importedrespids);
                   11910:                                 undef(%importedpartids);
                   11911:                             }
                   11912:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11913:                             if (@{$importedrespids{$importid}} > 0) {
                   11914:                                 $importedresponses = 1;
                   11915: # We need to get the original file and the imported file to get the response order correct
                   11916: # Load and inspect original file
                   11917:                                 if ($#origfiletagids<0) {
                   11918:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11919:                                     $origfile=&getfile($origfilelocation);
                   11920:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11921:                                 }
                   11922:                             }
                   11923:                         }
                   11924: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11925: # hash populated for imported library file
                   11926:                         %metaentry = %currmetaentry;
                   11927:                         undef(%currmetaentry);
1.1068    www      11928:                         if ($importmode eq 'problem') {
1.1069    www      11929: # Import as problem/response
1.1068    www      11930:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11931:                         } elsif ($importmode eq 'part') {
                   11932: # Import as part(s)
1.1069    www      11933:                            $importedparts=1;
                   11934: # We need to get the original file and the imported file to get the part order correct
                   11935: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11936: # Load and inspect original file if we didn't do that already
                   11937:                            if ($#origfiletagids<0) {
                   11938:                                undef(%importedrespids);
                   11939:                                undef(%importedpartids);
                   11940:                                if ($origfile eq '') {
                   11941:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11942:                                    $origfile=&getfile($origfilelocation);
                   11943:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11944:                                }
1.1070    www      11945:                            }
                   11946: 
1.1069    www      11947: # Load and inspect imported file
                   11948:                            my $impfile=&getfile($location);
                   11949:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11950:                            if ($#impfilepartids>=0) {
                   11951: # This problem had parts
1.1070    www      11952:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11953:                            } else {
                   11954: # Importing by turning a single problem into a problem part
                   11955: # It gets the import-tags ID as part-ID
                   11956:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11957:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11958:                            }
1.1068    www      11959:                         } else {
                   11960: # Normal import
                   11961:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11962:                            if (defined($token->[2]->{'id'})) {
                   11963:                               $unikey.='_'.$token->[2]->{'id'};
                   11964:                            }
1.1067    www      11965:                         }
                   11966: 
1.339     albertel 11967: 			if ($depthcount<20) {
1.736     albertel 11968: 			    my $metadata = 
                   11969: 				&metadata($uri,'keys', $location,$unikey,
                   11970: 					  $depthcount+1);
                   11971: 			    foreach my $meta (split(',',$metadata)) {
                   11972: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11973: 				$metathesekeys{$meta}=1;
1.339     albertel 11974: 			    }
1.1068    www      11975: 			
                   11976:                         }
1.1067    www      11977: 		    } else {
                   11978: #
                   11979: # Not importing, some other kind of non-package, non-library start tag
                   11980: # 
                   11981:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11982:                         if (defined($token->[2]->{'id'})) {
                   11983:                             $unikey.='_'.$token->[2]->{'id'};
                   11984:                         }
1.339     albertel 11985: 			if (defined($token->[2]->{'name'})) { 
                   11986: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11987: 			}
                   11988: 			$metathesekeys{$unikey}=1;
1.736     albertel 11989: 			foreach my $param (@{$token->[3]}) {
                   11990: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11991: 				$token->[2]->{$param};
1.339     albertel 11992: 			}
                   11993: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11994: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11995: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11996: 		 # only ws inside the tag, and not in default, so use default
                   11997: 		 # as value
1.599     albertel 11998: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11999: 			} elsif ( $internaltext =~ /\S/ ) {
                   12000: 		  # something interesting inside the tag
                   12001: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12002: 			} else {
1.908     albertel 12003: 		  # no interesting values, don't set a default
1.339     albertel 12004: 			}
1.172     www      12005: # end of not-a-package not-a-library import
1.339     albertel 12006: 		    }
1.172     www      12007: # end of not-a-package start tag
1.339     albertel 12008: 		}
1.172     www      12009: # the next is the end of "start tag"
1.339     albertel 12010: 	    }
                   12011: 	}
1.483     albertel 12012: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12013: 	$extension = lc($extension);
                   12014: 	if ($extension eq 'htm') { $extension='html'; }
                   12015: 
1.737     albertel 12016: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12017: 	    #no specific packages #how's our extension
                   12018: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12019: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12020: 					 \%metathesekeys);
                   12021: 	}
1.883     albertel 12022: 
                   12023: 	if (!exists($metaentry{':packages'})
                   12024: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12025: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12026: 		#no specific packages well let's get default then
                   12027: 		if ($key!~/^default&/) { next; }
1.488     albertel 12028: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12029: 					     \%metathesekeys);
                   12030: 	    }
                   12031: 	}
1.338     www      12032: # are there custom rights to evaluate
1.599     albertel 12033: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12034: 
1.338     www      12035:     #
                   12036:     # Importing a rights file here
1.339     albertel 12037:     #
                   12038: 	    unless ($depthcount) {
1.599     albertel 12039: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12040: 		my $dir=$filename;
                   12041: 		$dir=~s|[^/]*$||;
                   12042: 		$location=&filelocation($dir,$location);
1.736     albertel 12043: 		my $rights_metadata =
                   12044: 		    &metadata($uri,'keys',$location,'_rights',
                   12045: 			      $depthcount+1);
                   12046: 		foreach my $rights (split(',',$rights_metadata)) {
                   12047: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12048: 		    $metathesekeys{$rights}=1;
1.339     albertel 12049: 		}
                   12050: 	    }
                   12051: 	}
1.737     albertel 12052: 	# uniqifiy package listing
                   12053: 	my %seen;
                   12054: 	my @uniq_packages =
                   12055: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12056: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12057: 
1.1172.2.99  raeburn  12058:         if (($importedresponses) || ($importedparts)) {
                   12059:             if ($importedparts) {
1.1070    www      12060: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12061:                 $metaentry{':partorder'}='';
                   12062:                 $metathesekeys{'partorder'}=1;
                   12063:             }
                   12064:             if ($importedresponses) {
                   12065: # We had imported responses and need to rebuild responseorder
                   12066:                 $metaentry{':responseorder'}='';
                   12067:                 $metathesekeys{'responseorder'}=1;
                   12068:             }
                   12069:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12070:                 my $origid = $origfiletagids[$index+1];
                   12071:                 if ($origfiletagids[$index] eq 'part') {
                   12072: # Original part, part of the problem
                   12073:                     if ($importedparts) {
                   12074:                         $metaentry{':partorder'}.=','.$origid;
                   12075:                     }
                   12076:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12077:                     if ($importedparts) {
                   12078: # We have imported parts at this position
                   12079:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12080:                     }
                   12081:                     if ($importedresponses) {
                   12082: # We have imported responses at this position
                   12083:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12084:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12085:                         }
                   12086:                     }
                   12087:                 } else {
                   12088: # Original response item, part of the problem
                   12089:                     if ($importedresponses) {
                   12090:                         $metaentry{':responseorder'}.=','.$origid;
                   12091:                     }
                   12092:                 }
                   12093:             }
                   12094:             if ($importedparts) {
                   12095:                 $metaentry{':partorder'}=~s/^\,//;
                   12096:             }
                   12097:             if ($importedresponses) {
                   12098:                 $metaentry{':responseorder'}=~s/^\,//;
                   12099:             }
1.1070    www      12100:         }
                   12101: 
1.737     albertel 12102: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12103: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12104: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12105: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12106: # this is the end of "was not already recently cached
1.71      www      12107:     }
1.599     albertel 12108:     return $metaentry{':'.$what};
1.261     albertel 12109: }
                   12110: 
1.488     albertel 12111: sub metadata_create_package_def {
1.483     albertel 12112:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12113:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12114:     if ($subp eq 'default') { next; }
                   12115:     
1.599     albertel 12116:     if (defined($metaentry{':packages'})) {
                   12117: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12118:     } else {
1.599     albertel 12119: 	$metaentry{':packages'}=$package;
1.483     albertel 12120:     }
                   12121:     my $value=$packagetab{$key};
                   12122:     my $unikey;
                   12123:     $unikey='parameter_0_'.$name;
1.599     albertel 12124:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12125:     $$metathesekeys{$unikey}=1;
1.599     albertel 12126:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12127: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12128:     }
1.599     albertel 12129:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12130: 	$metaentry{':'.$unikey}=
                   12131: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12132:     }
                   12133: }
                   12134: 
1.261     albertel 12135: sub metadata_generate_part0 {
                   12136:     my ($metadata,$metacache,$uri) = @_;
                   12137:     my %allnames;
1.737     albertel 12138:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12139: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12140: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12141: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12142: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12143: 	    $allnames{$name}=$part;
                   12144: 	  }
                   12145: 	}
                   12146:     }
                   12147:     foreach my $name (keys(%allnames)) {
                   12148:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12149:       my $key=":parameter_0_$name";
1.261     albertel 12150:       $$metacache{"$key.part"}='0';
                   12151:       $$metacache{"$key.name"}=$name;
1.428     albertel 12152:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12153: 					   $allnames{$name}.'_'.$name.
                   12154: 					   '.type'};
1.428     albertel 12155:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12156: 			     '.display'};
1.644     www      12157:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12158:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12159:       $$metacache{"$key.display"}=$olddis;
                   12160:     }
1.71      www      12161: }
                   12162: 
1.764     albertel 12163: # ------------------------------------------------------ Devalidate title cache
                   12164: 
                   12165: sub devalidate_title_cache {
                   12166:     my ($url)=@_;
                   12167:     if (!$env{'request.course.id'}) { return; }
                   12168:     my $symb=&symbread($url);
                   12169:     if (!$symb) { return; }
                   12170:     my $key=$env{'request.course.id'}."\0".$symb;
                   12171:     &devalidate_cache_new('title',$key);
                   12172: }
                   12173: 
1.1014    droeschl 12174: # ------------------------------------------------- Get the title of a course
                   12175: 
                   12176: sub current_course_title {
                   12177:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12178: }
1.301     www      12179: # ------------------------------------------------- Get the title of a resource
                   12180: 
                   12181: sub gettitle {
                   12182:     my $urlsymb=shift;
                   12183:     my $symb=&symbread($urlsymb);
1.534     albertel 12184:     if ($symb) {
1.620     albertel 12185: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12186: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12187: 	if (defined($cached)) { 
                   12188: 	    return $result;
                   12189: 	}
1.534     albertel 12190: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12191: 	my $title='';
1.907     albertel 12192: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12193: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12194: 	} else {
                   12195: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12196: 		    &GDBM_READER(),0640)) {
                   12197: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12198: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12199: 		untie(%bighash);
                   12200: 	    }
1.534     albertel 12201: 	}
                   12202: 	$title=~s/\&colon\;/\:/gs;
                   12203: 	if ($title) {
1.1159    www      12204: # Remember both $symb and $title for dynamic metadata
                   12205:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12206:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12207: # Cache this title and then return it
1.599     albertel 12208: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12209: 	}
                   12210: 	$urlsymb=$url;
                   12211:     }
                   12212:     my $title=&metadata($urlsymb,'title');
                   12213:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12214:     return $title;
1.301     www      12215: }
1.613     albertel 12216: 
1.614     albertel 12217: sub get_slot {
                   12218:     my ($which,$cnum,$cdom)=@_;
                   12219:     if (!$cnum || !$cdom) {
1.790     albertel 12220: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12221: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12222: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12223:     }
1.703     albertel 12224:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12225:     my %slotinfo;
                   12226:     if (exists($remembered{$key})) {
                   12227: 	$slotinfo{$which} = $remembered{$key};
                   12228:     } else {
                   12229: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12230: 	&Apache::lonhomework::showhash(%slotinfo);
                   12231: 	my ($tmp)=keys(%slotinfo);
                   12232: 	if ($tmp=~/^error:/) { return (); }
                   12233: 	$remembered{$key} = $slotinfo{$which};
                   12234:     }
1.616     albertel 12235:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12236: 	return %{$slotinfo{$which}};
                   12237:     }
                   12238:     return $slotinfo{$which};
1.614     albertel 12239: }
1.1150    raeburn  12240: 
                   12241: sub get_reservable_slots {
                   12242:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12243:     my $now = time;
                   12244:     my $reservable_info;
                   12245:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12246:     if (exists($remembered{$key})) {
                   12247:         $reservable_info = $remembered{$key};
                   12248:     } else {
                   12249:         my %resv;
                   12250:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12251:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12252:         $reservable_info = \%resv;
                   12253:         $remembered{$key} = $reservable_info;
                   12254:     }
                   12255:     return $reservable_info;
                   12256: }
                   12257: 
                   12258: sub get_course_slots {
                   12259:     my ($cnum,$cdom) = @_;
                   12260:     my $hashid=$cnum.':'.$cdom;
                   12261:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12262:     if (defined($cached)) {
                   12263:         if (ref($result) eq 'HASH') {
                   12264:             return %{$result};
                   12265:         }
                   12266:     } else {
                   12267:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12268:         my ($tmp) = keys(%slots);
                   12269:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12270:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12271:             return %slots;
                   12272:         }
                   12273:     }
                   12274:     return;
                   12275: }
                   12276: 
                   12277: sub devalidate_slots_cache {
                   12278:     my ($cnum,$cdom)=@_;
                   12279:     my $hashid=$cnum.':'.$cdom;
                   12280:     &devalidate_cache_new('allslots',$hashid);
                   12281: }
                   12282: 
1.1172.2.8  raeburn  12283: sub get_coursechange {
                   12284:     my ($cdom,$cnum) = @_;
                   12285:     if ($cdom eq '' || $cnum eq '') {
                   12286:         return unless ($env{'request.course.id'});
                   12287:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12288:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12289:     }
                   12290:     my $hashid=$cdom.'_'.$cnum;
                   12291:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12292:     if ((defined($cached)) && ($change ne '')) {
                   12293:         return $change;
                   12294:     } else {
                   12295:         my %crshash;
                   12296:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12297:         if ($crshash{'internal.contentchange'} eq '') {
                   12298:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12299:             if ($change eq '') {
                   12300:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12301:                 $change = $crshash{'internal.created'};
                   12302:             }
                   12303:         } else {
                   12304:             $change = $crshash{'internal.contentchange'};
                   12305:         }
                   12306:         my $cachetime = 600;
                   12307:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12308:     }
                   12309:     return $change;
                   12310: }
                   12311: 
                   12312: sub devalidate_coursechange_cache {
                   12313:     my ($cnum,$cdom)=@_;
                   12314:     my $hashid=$cnum.':'.$cdom;
                   12315:     &devalidate_cache_new('crschange',$hashid);
                   12316: }
                   12317: 
1.31      www      12318: # ------------------------------------------------- Update symbolic store links
                   12319: 
                   12320: sub symblist {
                   12321:     my ($mapname,%newhash)=@_;
1.438     www      12322:     $mapname=&deversion(&declutter($mapname));
1.31      www      12323:     my %hash;
1.620     albertel 12324:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12325:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12326:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12327: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12328: 		next if ($url eq 'last_known'
                   12329: 			 && $env{'form.no_update_last_known'});
                   12330: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12331: 						    $newhash{$url}->[1],
                   12332: 						    $newhash{$url}->[0]);
1.191     harris41 12333:             }
1.31      www      12334:             if (untie(%hash)) {
                   12335: 		return 'ok';
                   12336:             }
                   12337:         }
                   12338:     }
                   12339:     return 'error';
1.212     www      12340: }
                   12341: 
                   12342: # --------------------------------------------------------------- Verify a symb
                   12343: 
                   12344: sub symbverify {
1.1172.2.11  raeburn  12345:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12346:     my $thisfn=$thisurl;
1.439     www      12347:     $thisfn=&declutter($thisfn);
1.215     www      12348: # direct jump to resource in page or to a sequence - will construct own symbs
                   12349:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12350: # check URL part
1.409     www      12351:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12352: 
1.431     www      12353:     unless ($url eq $thisfn) { return 0; }
1.213     www      12354: 
1.216     www      12355:     $symb=&symbclean($symb);
1.510     www      12356:     $thisurl=&deversion($thisurl);
1.439     www      12357:     $thisfn=&deversion($thisfn);
1.213     www      12358: 
                   12359:     my %bighash;
                   12360:     my $okay=0;
1.431     www      12361: 
1.620     albertel 12362:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12363:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12364:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12365:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12366:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12367:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12368:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12369:             }
                   12370:         }
                   12371:         my $ids;
1.1172.2.122  raeburn  12372:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12373:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12374:         } else {
                   12375:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12376:         }
1.1102    raeburn  12377:         unless ($ids) {
1.1172.2.13  raeburn  12378:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12379:             $ids=$bighash{$idkey};
1.216     www      12380:         }
                   12381:         if ($ids) {
                   12382: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12383:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12384:                 $symb =~ s/\?.+$//;
                   12385:             }
1.800     albertel 12386: 	    foreach my $id (split(/\,/,$ids)) {
                   12387: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12388:                if (
                   12389:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12390:    eq $symb) {
1.1172.2.11  raeburn  12391:                    if (ref($encstate)) {
                   12392:                        $$encstate = $bighash{'encrypted_'.$id};
                   12393:                    }
1.1172.2.13  raeburn  12394:                    if (($env{'request.role.adv'}) ||
                   12395:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12396:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12397:                        $okay=1;
                   12398:                        last;
                   12399:                    }
                   12400:                }
                   12401:            }
1.216     www      12402:         }
1.213     www      12403: 	untie(%bighash);
                   12404:     }
                   12405:     return $okay;
1.31      www      12406: }
                   12407: 
1.210     www      12408: # --------------------------------------------------------------- Clean-up symb
                   12409: 
                   12410: sub symbclean {
                   12411:     my $symb=shift;
1.568     albertel 12412:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12413: # remove version from map
                   12414:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12415: 
1.210     www      12416: # remove version from URL
                   12417:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12418: 
1.507     www      12419: # remove wrapper
                   12420: 
1.510     www      12421:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12422:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12423:     return $symb;
1.409     www      12424: }
                   12425: 
                   12426: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12427: 
                   12428: sub encode_symb {
                   12429:     my ($map,$resid,$url)=@_;
                   12430:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12431: }
1.409     www      12432: 
                   12433: sub decode_symb {
1.568     albertel 12434:     my $symb=shift;
                   12435:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12436:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12437:     return (&fixversion($map),$resid,&fixversion($url));
                   12438: }
                   12439: 
                   12440: sub fixversion {
                   12441:     my $fn=shift;
1.609     banghart 12442:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12443:     my %bighash;
                   12444:     my $uri=&clutter($fn);
1.620     albertel 12445:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12446: # is this cached?
1.599     albertel 12447:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12448:     if (defined($cached)) { return $result; }
                   12449: # unfortunately not cached, or expired
1.620     albertel 12450:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12451: 	    &GDBM_READER(),0640)) {
                   12452:  	if ($bighash{'version_'.$uri}) {
                   12453:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12454:  	    unless (($version eq 'mostrecent') || 
                   12455: 		    ($version==&getversion($uri))) {
1.440     www      12456:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12457:  	    }
                   12458:  	}
                   12459:  	untie %bighash;
1.413     www      12460:     }
1.599     albertel 12461:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12462: }
                   12463: 
                   12464: sub deversion {
                   12465:     my $url=shift;
                   12466:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12467:     return $url;
1.210     www      12468: }
                   12469: 
1.31      www      12470: # ------------------------------------------------------ Return symb list entry
                   12471: 
                   12472: sub symbread {
1.1172.2.126  raeburn  12473:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12474:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12475:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12476:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12477:         unless (ref($possibles) eq 'HASH') {
                   12478:             if ($ignorecachednull) {
                   12479:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12480:             } else {
                   12481:                 return $env{$cache_str};
                   12482:             }
1.1172.2.66  raeburn  12483:         }
                   12484:     }
1.242     www      12485: # no filename provided? try from environment
1.1172.2.54  raeburn  12486:     unless ($thisfn) {
1.620     albertel 12487:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12488:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12489:         }
                   12490:         $thisfn=$env{'request.filename'};
1.44      www      12491:     }
1.569     albertel 12492:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12493: # is that filename actually a symb? Verify, clean, and return
                   12494:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12495: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12496: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12497: 	}
1.242     www      12498:     }
1.44      www      12499:     $thisfn=declutter($thisfn);
1.31      www      12500:     my %hash;
1.37      www      12501:     my %bighash;
                   12502:     my $syval='';
1.620     albertel 12503:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12504:         my $targetfn = $thisfn;
1.609     banghart 12505:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12506:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12507:         }
1.687     albertel 12508: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12509: 	    $targetfn=$1;
                   12510: 	}
1.1172.2.128  raeburn  12511:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12512:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12513:                           &GDBM_READER(),0640)) {
                   12514: 	        $syval=$hash{$targetfn};
                   12515:                 untie(%hash);
                   12516:             }
1.1172.2.128  raeburn  12517:             if ($syval && $checkforblock) {
                   12518:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12519:                 if (@blockers) {
                   12520:                     $syval='';
                   12521:                 }
                   12522:             }
1.37      www      12523:         }
                   12524: # ---------------------------------------------------------- There was an entry
                   12525:         if ($syval) {
1.601     albertel 12526: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12527: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12528: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12529: 		    #return $env{$cache_str}='';
1.601     albertel 12530: 		#}    
                   12531: 		#$syval.=$1;
                   12532: 	    #}
1.37      www      12533:         } else {
                   12534: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12535:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12536:                             &GDBM_READER(),0640)) {
1.37      www      12537: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12538:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12539:               unless ($ids) { 
                   12540:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12541:               }
                   12542:               unless ($ids) {
                   12543: # alias?
                   12544: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12545:               }
1.37      www      12546:               if ($ids) {
                   12547: # ------------------------------------------------------------------- Has ID(s)
                   12548:                  my @possibilities=split(/\,/,$ids);
1.39      www      12549:                  if ($#possibilities==0) {
                   12550: # ----------------------------------------------- There is only one possibility
1.37      www      12551: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12552: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12553: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12554:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12555:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12556:                              $possibles->{$syval} = 1;
                   12557:                          }
1.1172.2.66  raeburn  12558:                      }
                   12559:                      if ($checkforblock) {
1.1172.2.126  raeburn  12560:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12561:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12562:                              if (@blockers) {
                   12563:                                  $syval = '';
                   12564:                                  untie(%bighash);
                   12565:                                  return $env{$cache_str}='';
                   12566:                              }
1.1172.2.66  raeburn  12567:                          }
                   12568:                      }
                   12569:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12570: # ------------------------------------------ There is more than one possibility
                   12571:                      my $realpossible=0;
1.800     albertel 12572:                      foreach my $id (@possibilities) {
                   12573: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12574:                          my $canaccess;
                   12575:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12576:                              $canaccess = 1;
                   12577:                          } else {
                   12578:                              $canaccess = &allowed('bre',$file);
                   12579:                          }
                   12580:                          if ($canaccess) {
                   12581:          		     my ($mapid,$resid)=split(/\./,$id);
                   12582:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12583:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12584:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12585:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12586:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12587:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12588:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12589:                                      if (@blockers > 0) {
                   12590:                                          $syval = '';
                   12591:                                      } else {
1.1172.2.66  raeburn  12592:                                          $syval = $poss_syval;
                   12593:                                          $realpossible++;
                   12594:                                      }
                   12595:                                  } else {
                   12596:                                      $syval = $poss_syval;
                   12597:                                      $realpossible++;
                   12598:                                  }
1.1172.2.126  raeburn  12599:                                  if ($syval) {
                   12600:                                      if (ref($possibles) eq 'HASH') {
                   12601:                                          $possibles->{$syval} = 1;
                   12602:                                      }
                   12603:                                  }
1.1172.2.66  raeburn  12604:                              }
1.39      www      12605: 			 }
1.191     harris41 12606:                      }
1.39      www      12607: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12608:                  } else {
                   12609:                      $syval='';
1.37      www      12610:                  }
                   12611: 	      }
1.1172.2.66  raeburn  12612:               untie(%bighash);
1.481     raeburn  12613:            }
1.31      www      12614:         }
1.62      www      12615:         if ($syval) {
1.1172.2.128  raeburn  12616: 	    return $env{$cache_str}=$syval;
1.62      www      12617:         }
1.31      www      12618:     }
1.949     raeburn  12619:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12620:     return $env{$cache_str}='';
1.31      www      12621: }
                   12622: 
                   12623: # ---------------------------------------------------------- Return random seed
                   12624: 
1.32      www      12625: sub numval {
                   12626:     my $txt=shift;
                   12627:     $txt=~tr/A-J/0-9/;
                   12628:     $txt=~tr/a-j/0-9/;
                   12629:     $txt=~tr/K-T/0-9/;
                   12630:     $txt=~tr/k-t/0-9/;
                   12631:     $txt=~tr/U-Z/0-5/;
                   12632:     $txt=~tr/u-z/0-5/;
                   12633:     $txt=~s/\D//g;
1.564     albertel 12634:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12635:     return int($txt);
1.368     albertel 12636: }
                   12637: 
1.484     albertel 12638: sub numval2 {
                   12639:     my $txt=shift;
                   12640:     $txt=~tr/A-J/0-9/;
                   12641:     $txt=~tr/a-j/0-9/;
                   12642:     $txt=~tr/K-T/0-9/;
                   12643:     $txt=~tr/k-t/0-9/;
                   12644:     $txt=~tr/U-Z/0-5/;
                   12645:     $txt=~tr/u-z/0-5/;
                   12646:     $txt=~s/\D//g;
                   12647:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12648:     my $total;
                   12649:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12650:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12651:     return int($total);
                   12652: }
                   12653: 
1.575     albertel 12654: sub numval3 {
                   12655:     use integer;
                   12656:     my $txt=shift;
                   12657:     $txt=~tr/A-J/0-9/;
                   12658:     $txt=~tr/a-j/0-9/;
                   12659:     $txt=~tr/K-T/0-9/;
                   12660:     $txt=~tr/k-t/0-9/;
                   12661:     $txt=~tr/U-Z/0-5/;
                   12662:     $txt=~tr/u-z/0-5/;
                   12663:     $txt=~s/\D//g;
                   12664:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12665:     my $total;
                   12666:     foreach my $val (@txts) { $total+=$val; }
                   12667:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12668:     return $total;
                   12669: }
                   12670: 
1.675     albertel 12671: sub digest {
                   12672:     my ($data)=@_;
                   12673:     my $digest=&Digest::MD5::md5($data);
                   12674:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12675:     my ($e,$f);
                   12676:     {
                   12677:         use integer;
                   12678:         $e=($a+$b);
                   12679:         $f=($c+$d);
                   12680:         if ($_64bit) {
                   12681:             $e=(($e<<32)>>32);
                   12682:             $f=(($f<<32)>>32);
                   12683:         }
                   12684:     }
                   12685:     if (wantarray) {
                   12686: 	return ($e,$f);
                   12687:     } else {
                   12688: 	my $g;
                   12689: 	{
                   12690: 	    use integer;
                   12691: 	    $g=($e+$f);
                   12692: 	    if ($_64bit) {
                   12693: 		$g=(($g<<32)>>32);
                   12694: 	    }
                   12695: 	}
                   12696: 	return $g;
                   12697:     }
                   12698: }
                   12699: 
1.368     albertel 12700: sub latest_rnd_algorithm_id {
1.675     albertel 12701:     return '64bit5';
1.366     albertel 12702: }
1.32      www      12703: 
1.503     albertel 12704: sub get_rand_alg {
                   12705:     my ($courseid)=@_;
1.790     albertel 12706:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12707:     if ($courseid) {
1.620     albertel 12708: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12709:     }
                   12710:     return &latest_rnd_algorithm_id();
                   12711: }
                   12712: 
1.562     albertel 12713: sub validCODE {
                   12714:     my ($CODE)=@_;
                   12715:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12716:     return 0;
                   12717: }
                   12718: 
1.491     albertel 12719: sub getCODE {
1.620     albertel 12720:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12721:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12722: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12723: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12724: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12725:     }
                   12726:     return undef;
                   12727: }
1.1133    foxr     12728: #
                   12729: #  Determines the random seed for a specific context:
                   12730: #
                   12731: # parameters:
                   12732: #   symb      - in course context the symb for the seed.
                   12733: #   course_id - The course id of the form domain_coursenum.
                   12734: #   domain    - Domain for the user.
                   12735: #   course    - Course for the user.
                   12736: #   cenv      - environment of the course.
                   12737: #
                   12738: # NOTE:
                   12739: #   All parameters are picked out of the environment if missing
                   12740: #   or not defined.
                   12741: #   If a symb cannot be determined the current time is used instead.
                   12742: #
                   12743: #  For a given well defined symb, courside, domain, username,
                   12744: #  and course environment, the seed is reproducible.
                   12745: #
1.31      www      12746: sub rndseed {
1.1133    foxr     12747:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12748:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12749:     if (!defined($symb)) {
1.366     albertel 12750: 	unless ($symb=$wsymb) { return time; }
                   12751:     }
1.1146    foxr     12752:     if (!defined $courseid) { 
                   12753: 	$courseid=$wcourseid; 
                   12754:     }
                   12755:     if (!defined $domain) { $domain=$wdomain; }
                   12756:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12757: 
                   12758:     my $which;
                   12759:     if (defined($cenv->{'rndseed'})) {
                   12760: 	$which = $cenv->{'rndseed'};
                   12761:     } else {
                   12762: 	$which =&get_rand_alg($courseid);
                   12763:     }
1.491     albertel 12764:     if (defined(&getCODE())) {
1.675     albertel 12765: 	if ($which eq '64bit5') {
                   12766: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12767: 	} elsif ($which eq '64bit4') {
1.575     albertel 12768: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12769: 	} else {
                   12770: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12771: 	}
1.675     albertel 12772:     } elsif ($which eq '64bit5') {
                   12773: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12774:     } elsif ($which eq '64bit4') {
                   12775: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12776:     } elsif ($which eq '64bit3') {
                   12777: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12778:     } elsif ($which eq '64bit2') {
                   12779: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12780:     } elsif ($which eq '64bit') {
                   12781: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12782:     }
                   12783:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12784: }
                   12785: 
                   12786: sub rndseed_32bit {
                   12787:     my ($symb,$courseid,$domain,$username)=@_;
                   12788:     {
                   12789: 	use integer;
                   12790: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12791: 	my $symbseed=numval($symb) << 22;
                   12792: 	my $namechck=unpack("%32C*",$username) << 17;
                   12793: 	my $nameseed=numval($username) << 12;
                   12794: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12795: 	my $courseseed=unpack("%32C*",$courseid);
                   12796: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12797: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12798: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12799: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12800: 	return $num;
                   12801:     }
                   12802: }
                   12803: 
                   12804: sub rndseed_64bit {
                   12805:     my ($symb,$courseid,$domain,$username)=@_;
                   12806:     {
                   12807: 	use integer;
                   12808: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12809: 	my $symbseed=numval($symb) << 10;
                   12810: 	my $namechck=unpack("%32S*",$username);
                   12811: 	
                   12812: 	my $nameseed=numval($username) << 21;
                   12813: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12814: 	my $courseseed=unpack("%32S*",$courseid);
                   12815: 	
                   12816: 	my $num1=$symbchck+$symbseed+$namechck;
                   12817: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12818: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12819: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12820: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12821: 	return "$num1,$num2";
1.155     albertel 12822:     }
1.366     albertel 12823: }
                   12824: 
1.443     albertel 12825: sub rndseed_64bit2 {
                   12826:     my ($symb,$courseid,$domain,$username)=@_;
                   12827:     {
                   12828: 	use integer;
                   12829: 	# strings need to be an even # of cahracters long, it it is odd the
                   12830:         # last characters gets thrown away
                   12831: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12832: 	my $symbseed=numval($symb) << 10;
                   12833: 	my $namechck=unpack("%32S*",$username.' ');
                   12834: 	
                   12835: 	my $nameseed=numval($username) << 21;
1.501     albertel 12836: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12837: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12838: 	
                   12839: 	my $num1=$symbchck+$symbseed+$namechck;
                   12840: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12841: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12842: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12843: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12844: 	return "$num1,$num2";
                   12845:     }
                   12846: }
                   12847: 
                   12848: sub rndseed_64bit3 {
                   12849:     my ($symb,$courseid,$domain,$username)=@_;
                   12850:     {
                   12851: 	use integer;
                   12852: 	# strings need to be an even # of cahracters long, it it is odd the
                   12853:         # last characters gets thrown away
                   12854: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12855: 	my $symbseed=numval2($symb) << 10;
                   12856: 	my $namechck=unpack("%32S*",$username.' ');
                   12857: 	
                   12858: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12859: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12860: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12861: 	
                   12862: 	my $num1=$symbchck+$symbseed+$namechck;
                   12863: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12865: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12866: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12867: 	
1.503     albertel 12868: 	return "$num1:$num2";
1.443     albertel 12869:     }
                   12870: }
                   12871: 
1.575     albertel 12872: sub rndseed_64bit4 {
                   12873:     my ($symb,$courseid,$domain,$username)=@_;
                   12874:     {
                   12875: 	use integer;
                   12876: 	# strings need to be an even # of cahracters long, it it is odd the
                   12877:         # last characters gets thrown away
                   12878: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12879: 	my $symbseed=numval3($symb) << 10;
                   12880: 	my $namechck=unpack("%32S*",$username.' ');
                   12881: 	
                   12882: 	my $nameseed=numval3($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 :$num1:$num2:$_64bit");
1.575     albertel 12890: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12891: 	
1.575     albertel 12892: 	return "$num1:$num2";
                   12893:     }
                   12894: }
                   12895: 
1.675     albertel 12896: sub rndseed_64bit5 {
                   12897:     my ($symb,$courseid,$domain,$username)=@_;
                   12898:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12899:     return "$num1:$num2";
                   12900: }
                   12901: 
1.366     albertel 12902: sub rndseed_CODE_64bit {
                   12903:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12904:     {
1.366     albertel 12905: 	use integer;
1.443     albertel 12906: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12907: 	my $symbseed=numval2($symb);
1.491     albertel 12908: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12909: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12910: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12911: 	my $num1=$symbseed+$CODEchck;
                   12912: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12913: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12914: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12915: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12916: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12917: 	return "$num1:$num2";
1.366     albertel 12918:     }
                   12919: }
                   12920: 
1.575     albertel 12921: sub rndseed_CODE_64bit4 {
                   12922:     my ($symb,$courseid,$domain,$username)=@_;
                   12923:     {
                   12924: 	use integer;
                   12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12926: 	my $symbseed=numval3($symb);
                   12927: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12928: 	my $CODEseed=numval3(&getCODE());
                   12929: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12930: 	my $num1=$symbseed+$CODEchck;
                   12931: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12932: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12933: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12934: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12935: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12936: 	return "$num1:$num2";
                   12937:     }
                   12938: }
                   12939: 
1.675     albertel 12940: sub rndseed_CODE_64bit5 {
                   12941:     my ($symb,$courseid,$domain,$username)=@_;
                   12942:     my $code = &getCODE();
                   12943:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12944:     return "$num1:$num2";
                   12945: }
                   12946: 
1.366     albertel 12947: sub setup_random_from_rndseed {
                   12948:     my ($rndseed)=@_;
1.503     albertel 12949:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12950: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12951:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12952:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12953:         } else {
                   12954:             &Math::Random::random_set_seed($num1,$num2);
                   12955:         }
1.366     albertel 12956:     } else {
                   12957: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12958:     }
1.36      albertel 12959: }
                   12960: 
1.474     albertel 12961: sub latest_receipt_algorithm_id {
1.835     albertel 12962:     return 'receipt3';
1.474     albertel 12963: }
                   12964: 
1.480     www      12965: sub recunique {
                   12966:     my $fucourseid=shift;
                   12967:     my $unique;
1.835     albertel 12968:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12969: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12970: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12971:     } else {
                   12972: 	$unique=$perlvar{'lonReceipt'};
                   12973:     }
                   12974:     return unpack("%32C*",$unique);
                   12975: }
                   12976: 
                   12977: sub recprefix {
                   12978:     my $fucourseid=shift;
                   12979:     my $prefix;
1.835     albertel 12980:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12981: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12982: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12983:     } else {
                   12984: 	$prefix=$perlvar{'lonHostID'};
                   12985:     }
                   12986:     return unpack("%32C*",$prefix);
                   12987: }
                   12988: 
1.76      www      12989: sub ireceipt {
1.474     albertel 12990:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12991: 
                   12992:     my $return =&recprefix($fucourseid).'-';
                   12993: 
                   12994:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12995: 	$env{'request.state'} eq 'construct') {
                   12996: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12997: 	return $return;
                   12998:     }
                   12999: 
1.76      www      13000:     my $cuname=unpack("%32C*",$funame);
                   13001:     my $cudom=unpack("%32C*",$fudom);
                   13002:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13003:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13004:     my $cunique=&recunique($fucourseid);
1.474     albertel 13005:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13007: 
1.790     albertel 13008: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13009: 			       
                   13010: 	$return.= ($cunique%$cuname+
                   13011: 		   $cunique%$cudom+
                   13012: 		   $cusymb%$cuname+
                   13013: 		   $cusymb%$cudom+
                   13014: 		   $cucourseid%$cuname+
                   13015: 		   $cucourseid%$cudom+
                   13016: 		   $cpart%$cuname+
                   13017: 		   $cpart%$cudom);
                   13018:     } else {
                   13019: 	$return.= ($cunique%$cuname+
                   13020: 		   $cunique%$cudom+
                   13021: 		   $cusymb%$cuname+
                   13022: 		   $cusymb%$cudom+
                   13023: 		   $cucourseid%$cuname+
                   13024: 		   $cucourseid%$cudom);
                   13025:     }
                   13026:     return $return;
1.76      www      13027: }
                   13028: 
                   13029: sub receipt {
1.474     albertel 13030:     my ($part)=@_;
1.790     albertel 13031:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13032:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13033: }
1.260     ng       13034: 
1.790     albertel 13035: sub whichuser {
                   13036:     my ($passedsymb)=@_;
                   13037:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13038:     if (defined($env{'form.grade_symb'})) {
                   13039: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13040: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13041: 	if (!$allowed &&
                   13042: 	    exists($env{'request.course.sec'}) &&
                   13043: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13044: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13045: 			      '/'.$env{'request.course.sec'});
                   13046: 	}
                   13047: 	if ($allowed) {
                   13048: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13049: 	    $courseid=$tmp_courseid;
                   13050: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13051: 	    ($name)=&get_env_multiple('form.grade_username');
                   13052: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13053: 	}
                   13054:     }
                   13055:     if (!$passedsymb) {
                   13056: 	$symb=&symbread();
                   13057:     } else {
                   13058: 	$symb=$passedsymb;
                   13059:     }
                   13060:     $courseid=$env{'request.course.id'};
                   13061:     $domain=$env{'user.domain'};
                   13062:     $name=$env{'user.name'};
                   13063:     if ($name eq 'public' && $domain eq 'public') {
                   13064: 	if (!defined($env{'form.username'})) {
                   13065: 	    $env{'form.username'}.=time.rand(10000000);
                   13066: 	}
                   13067: 	$name.=$env{'form.username'};
                   13068:     }
                   13069:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13070: 
                   13071: }
                   13072: 
1.36      albertel 13073: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13074: # returns either the contents of the file or 
                   13075: # -1 if the file doesn't exist
1.481     raeburn  13076: #
                   13077: # if the target is a file that was uploaded via DOCS, 
                   13078: # a check will be made to see if a current copy exists on the local server,
                   13079: # if it does this will be served, otherwise a copy will be retrieved from
                   13080: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13081: # the local server.   
1.472     albertel 13082: 
1.36      albertel 13083: sub getfile {
1.538     albertel 13084:     my ($file) = @_;
1.609     banghart 13085:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13086:     &repcopy($file);
                   13087:     return &readfile($file);
                   13088: }
                   13089: 
                   13090: sub repcopy_userfile {
                   13091:     my ($file)=@_;
1.1142    raeburn  13092:     my $londocroot = $perlvar{'lonDocRoot'};
                   13093:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13094:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13095:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13096: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13097:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13098:     if (-e "$file") {
1.828     www      13099: # we already have a local copy, check it out
1.538     albertel 13100: 	my @fileinfo = stat($file);
1.828     www      13101: 	my $rtncode;
                   13102: 	my $info;
1.538     albertel 13103: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13104: 	if ($lwpresp ne 'ok') {
1.828     www      13105: # there is no such file anymore, even though we had a local copy
1.482     albertel 13106: 	    if ($rtncode eq '404') {
1.538     albertel 13107: 		unlink($file);
1.482     albertel 13108: 	    }
                   13109: 	    return -1;
                   13110: 	}
                   13111: 	if ($info < $fileinfo[9]) {
1.828     www      13112: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13113: 	    return 'ok';
1.828     www      13114: 	} else {
                   13115: # the file is outdated, get rid of it
                   13116: 	    unlink($file);
1.482     albertel 13117: 	}
1.828     www      13118:     }
                   13119: # one way or the other, at this point, we don't have the file
                   13120: # construct the correct path for the file
                   13121:     my @parts = ($cdom,$cnum); 
                   13122:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13123: 	push @parts, split(/\//,$1);
                   13124:     }
                   13125:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13126:     foreach my $part (@parts) {
                   13127: 	$path .= '/'.$part;
                   13128: 	if (!-e $path) {
                   13129: 	    mkdir($path,0770);
1.482     albertel 13130: 	}
                   13131:     }
1.828     www      13132: # now the path exists for sure
                   13133: # get a user agent
                   13134:     my $ua=new LWP::UserAgent;
                   13135:     my $transferfile=$file.'.in.transfer';
                   13136: # FIXME: this should flock
                   13137:     if (-e $transferfile) { return 'ok'; }
                   13138:     my $request;
                   13139:     $uri=~s/^\///;
1.980     raeburn  13140:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13141:     my $hostname = &hostname($homeserver);
1.980     raeburn  13142:     my $protocol = $protocol{$homeserver};
                   13143:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13144:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13145:     my $response=$ua->request($request,$transferfile);
                   13146: # did it work?
                   13147:     if ($response->is_error()) {
                   13148: 	unlink($transferfile);
                   13149: 	&logthis("Userfile repcopy failed for $uri");
                   13150: 	return -1;
                   13151:     }
                   13152: # worked, rename the transfer file
                   13153:     rename($transferfile,$file);
1.607     raeburn  13154:     return 'ok';
1.481     raeburn  13155: }
                   13156: 
1.517     albertel 13157: sub tokenwrapper {
                   13158:     my $uri=shift;
1.980     raeburn  13159:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13160:     $uri=~s|^/||;
1.620     albertel 13161:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13162:     my $token=$1;
1.552     albertel 13163:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13164:     if ($udom && $uname && $file) {
                   13165: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13166:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13167:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13168:         my $hostname = &hostname($homeserver);
1.980     raeburn  13169:         my $protocol = $protocol{$homeserver};
                   13170:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13171:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13172:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13173:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13174:     } else {
                   13175:         return '/adm/notfound.html';
                   13176:     }
                   13177: }
                   13178: 
1.828     www      13179: # call with reqtype HEAD: get last modification time
                   13180: # call with reqtype GET: get the file contents
                   13181: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13182: #
1.481     raeburn  13183: sub getuploaded {
                   13184:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13185:     $uri=~s/^\///;
1.980     raeburn  13186:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13187:     my $hostname = &hostname($homeserver);
1.980     raeburn  13188:     my $protocol = $protocol{$homeserver};
                   13189:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13190:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13191:     my $ua=new LWP::UserAgent;
                   13192:     my $request=new HTTP::Request($reqtype,$uri);
                   13193:     my $response=$ua->request($request);
                   13194:     $$rtncode = $response->code;
1.482     albertel 13195:     if (! $response->is_success()) {
                   13196: 	return 'failed';
                   13197:     }      
                   13198:     if ($reqtype eq 'HEAD') {
1.486     www      13199: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13200:     } elsif ($reqtype eq 'GET') {
                   13201: 	$$info = $response->content;
1.472     albertel 13202:     }
1.482     albertel 13203:     return 'ok';
1.36      albertel 13204: }
                   13205: 
1.481     raeburn  13206: sub readfile {
                   13207:     my $file = shift;
                   13208:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13209:     my $fh;
1.1172.2.96  raeburn  13210:     open($fh,"<",$file);
1.481     raeburn  13211:     my $a='';
1.800     albertel 13212:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13213:     return $a;
                   13214: }
                   13215: 
1.36      albertel 13216: sub filelocation {
1.590     banghart 13217:     my ($dir,$file) = @_;
                   13218:     my $location;
                   13219:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13220: 
                   13221:     if ($file =~ m-^/adm/-) {
                   13222: 	$file=~s-^/adm/wrapper/-/-;
                   13223: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13224:     }
1.882     albertel 13225: 
1.1139    www      13226:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13227:         $location = $file;
1.609     banghart 13228:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13229:         my ($udom,$uname,$filename)=
1.811     albertel 13230:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13231:         my $home=&homeserver($uname,$udom);
                   13232:         my $is_me=0;
                   13233:         my @ids=&current_machine_ids();
                   13234:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13235:         if ($is_me) {
1.1117    foxr     13236:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13237:         } else {
                   13238:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13239:   	      $udom.'/'.$uname.'/'.$filename;
                   13240:         }
1.882     albertel 13241:     } elsif ($file =~ m-^/adm/-) {
                   13242: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13243:     } else {
                   13244:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13245:         $file=~s:^/(res|priv)/:/:;
                   13246:         my $space=$1;
1.590     banghart 13247:         if ( !( $file =~ m:^/:) ) {
                   13248:             $location = $dir. '/'.$file;
                   13249:         } else {
1.1142    raeburn  13250:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13251:         }
1.59      albertel 13252:     }
1.590     banghart 13253:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13254:     while ($location=~m{/\.\./}) {
                   13255: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13256: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13257: 	} else {
                   13258: 	    $location=~ s{/\.\./}{/}g;
                   13259: 	}
                   13260:     } #remove dir/..
1.590     banghart 13261:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13262:     return $location;
1.46      www      13263: }
1.36      albertel 13264: 
1.46      www      13265: sub hreflocation {
                   13266:     my ($dir,$file)=@_;
1.980     raeburn  13267:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13268: 	$file=filelocation($dir,$file);
1.700     albertel 13269:     } elsif ($file=~m-^/adm/-) {
                   13270: 	$file=~s-^/adm/wrapper/-/-;
                   13271: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13272:     }
                   13273:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13274: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13275:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13276: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13277: 	        {/uploaded/$1/$2/}x;
1.46      www      13278:     }
1.913     albertel 13279:     if ($file=~ m{^/userfiles/}) {
                   13280: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13281:     }
1.462     albertel 13282:     return $file;
1.465     albertel 13283: }
                   13284: 
1.1139    www      13285: 
                   13286: 
                   13287: 
                   13288: 
1.465     albertel 13289: sub current_machine_domains {
1.853     albertel 13290:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13291: }
                   13292: 
                   13293: sub machine_domains {
                   13294:     my ($hostname) = @_;
1.465     albertel 13295:     my @domains;
1.838     albertel 13296:     my %hostname = &all_hostnames();
1.465     albertel 13297:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13298: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13299: 	if ($hostname eq $name) {
1.844     albertel 13300: 	    push(@domains,&host_domain($id));
1.465     albertel 13301: 	}
                   13302:     }
                   13303:     return @domains;
                   13304: }
                   13305: 
                   13306: sub current_machine_ids {
1.853     albertel 13307:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13308: }
                   13309: 
                   13310: sub machine_ids {
                   13311:     my ($hostname) = @_;
                   13312:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13313:     my @ids;
1.888     albertel 13314:     my %name_to_host = &all_names();
1.889     albertel 13315:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13316: 	return @{ $name_to_host{$hostname} };
                   13317:     }
                   13318:     return;
1.31      www      13319: }
                   13320: 
1.824     raeburn  13321: sub additional_machine_domains {
                   13322:     my @domains;
1.1172.2.96  raeburn  13323:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13324:     while( my $line = <$fh>) {
                   13325:         $line =~ s/\s//g;
                   13326:         push(@domains,$line);
                   13327:     }
                   13328:     return @domains;
                   13329: }
                   13330: 
                   13331: sub default_login_domain {
                   13332:     my $domain = $perlvar{'lonDefDomain'};
                   13333:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13334:     foreach my $posdom (&current_machine_domains(),
                   13335:                         &additional_machine_domains()) {
                   13336:         if (lc($posdom) eq lc($testdomain)) {
                   13337:             $domain=$posdom;
                   13338:             last;
                   13339:         }
                   13340:     }
                   13341:     return $domain;
                   13342: }
                   13343: 
1.1172.2.106  raeburn  13344: sub shared_institution {
                   13345:     my ($dom) = @_;
                   13346:     my $same_intdom;
                   13347:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13348:     if ($hostintdom ne '') {
                   13349:         my %iphost = &get_iphost();
                   13350:         my $primary_id = &domain($dom,'primary');
                   13351:         my $primary_ip = &get_host_ip($primary_id);
                   13352:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13353:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13354:                 my $intdom = &internet_dom($id);
                   13355:                 if ($intdom eq $hostintdom) {
                   13356:                     $same_intdom = 1;
                   13357:                     last;
                   13358:                 }
                   13359:             }
                   13360:         }
                   13361:     }
                   13362:     return $same_intdom;
                   13363: }
                   13364: 
1.1172.2.120  raeburn  13365: sub uses_sts {
                   13366:     my ($ignore_cache) = @_;
                   13367:     my $lonhost = $perlvar{'lonHostID'};
                   13368:     my $hostname = &hostname($lonhost);
                   13369:     my $sts_on;
                   13370:     if ($protocol{$lonhost} eq 'https') {
                   13371:         my $cachetime = 12*3600;
                   13372:         if (!$ignore_cache) {
                   13373:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13374:             if (defined($cached)) {
                   13375:                 return $sts_on;
                   13376:             }
                   13377:         }
1.1172.2.121  raeburn  13378:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13379:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13380:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13381:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13382:         if ($response->is_success) {
                   13383:             my $has_sts = $response->header('Strict-Transport-Security');
                   13384:             if ($has_sts eq '') {
                   13385:                 $sts_on = 0;
                   13386:             } else {
                   13387:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13388:                     my $maxage = $1;
                   13389:                     if ($maxage) {
                   13390:                         $sts_on = 1;
                   13391:                     } else {
                   13392:                         $sts_on = 0;
                   13393:                     }
                   13394:                 } else {
                   13395:                     $sts_on = 0;
                   13396:                 }
                   13397:             }
                   13398:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13399:         }
                   13400:     }
                   13401:     return;
                   13402: }
                   13403: 
1.31      www      13404: # ------------------------------------------------------------- Declutters URLs
                   13405: 
                   13406: sub declutter {
                   13407:     my $thisfn=shift;
1.569     albertel 13408:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13409:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13410:         $thisfn=~s{^/home/httpd/html}{};
                   13411:     }
1.31      www      13412:     $thisfn=~s/^\///;
1.697     albertel 13413:     $thisfn=~s|^adm/wrapper/||;
                   13414:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13415:     $thisfn=~s/^res\///;
1.1172    bisitz   13416:     $thisfn=~s/^priv\///;
1.1032    raeburn  13417:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13418:         $thisfn=~s/\?.+$//;
                   13419:     }
1.268     www      13420:     return $thisfn;
                   13421: }
                   13422: 
                   13423: # ------------------------------------------------------------- Clutter up URLs
                   13424: 
                   13425: sub clutter {
                   13426:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13427:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13428: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13429:        $thisfn='/res'.$thisfn; 
                   13430:     }
1.1031    raeburn  13431:     if ($thisfn !~m|^/adm|) {
                   13432: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13433: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13434: 	} else {
                   13435: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13436: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13437: 	    if ($embstyle eq 'ssi'
                   13438: 		|| ($embstyle eq 'hdn')
                   13439: 		|| ($embstyle eq 'rat')
                   13440: 		|| ($embstyle eq 'prv')
                   13441: 		|| ($embstyle eq 'ign')) {
                   13442: 		#do nothing with these
                   13443: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13444: 		|| ($embstyle eq 'emb')
                   13445: 		|| ($embstyle eq 'wrp')) {
                   13446: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13447: 	    } elsif ($embstyle eq 'unk'
                   13448: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13449: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13450: 	    } else {
1.718     www      13451: #		&logthis("Got a blank emb style");
1.695     albertel 13452: 	    }
1.694     albertel 13453: 	}
                   13454:     }
1.31      www      13455:     return $thisfn;
1.12      www      13456: }
                   13457: 
1.787     albertel 13458: sub clutter_with_no_wrapper {
                   13459:     my $uri = &clutter(shift);
                   13460:     if ($uri =~ m-^/adm/-) {
                   13461: 	$uri =~ s-^/adm/wrapper/-/-;
                   13462: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13463:     }
                   13464:     return $uri;
                   13465: }
                   13466: 
1.557     albertel 13467: sub freeze_escape {
                   13468:     my ($value)=@_;
                   13469:     if (ref($value)) {
                   13470: 	$value=&nfreeze($value);
                   13471: 	return '__FROZEN__'.&escape($value);
                   13472:     }
                   13473:     return &escape($value);
                   13474: }
                   13475: 
1.11      www      13476: 
1.557     albertel 13477: sub thaw_unescape {
                   13478:     my ($value)=@_;
                   13479:     if ($value =~ /^__FROZEN__/) {
                   13480: 	substr($value,0,10,undef);
                   13481: 	$value=&unescape($value);
                   13482: 	return &thaw($value);
                   13483:     }
                   13484:     return &unescape($value);
                   13485: }
                   13486: 
1.436     albertel 13487: sub correct_line_ends {
                   13488:     my ($result)=@_;
                   13489:     $$result =~s/\r\n/\n/mg;
                   13490:     $$result =~s/\r/\n/mg;
1.415     albertel 13491: }
1.1       albertel 13492: # ================================================================ Main Program
                   13493: 
1.184     www      13494: sub goodbye {
1.204     albertel 13495:    &logthis("Starting Shut down");
1.443     albertel 13496: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13497:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13498: #converted
1.599     albertel 13499: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13500:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13501: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13502: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13503: #1.1 only
1.870     albertel 13504: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13505: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13506: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13507: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13508:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13509:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13510:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13511:    &flushcourselogs();
                   13512:    &logthis("Shutting down");
                   13513: }
                   13514: 
1.852     albertel 13515: sub get_dns {
1.1172.2.17  raeburn  13516:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13517:     if (!$ignore_cache) {
                   13518: 	my ($content,$cached)=
                   13519: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13520: 	if ($cached) {
1.1172.2.17  raeburn  13521: 	    &$func($content,$hashref);
1.869     albertel 13522: 	    return;
                   13523: 	}
                   13524:     }
                   13525: 
                   13526:     my %alldns;
1.1172.2.96  raeburn  13527:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13528:         foreach my $dns (<$config>) {
                   13529: 	    next if ($dns !~ /^\^(\S*)/x);
                   13530:             my $line = $1;
                   13531:             my ($host,$protocol) = split(/:/,$line);
                   13532:             if ($protocol ne 'https') {
                   13533:                 $protocol = 'http';
                   13534:             }
                   13535: 	    $alldns{$host} = $protocol;
1.979     raeburn  13536:         }
1.1172.2.96  raeburn  13537:         close($config);
1.869     albertel 13538:     }
                   13539:     while (%alldns) {
1.1172.2.52  raeburn  13540: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13541: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13542:         $ua->timeout(30);
1.979     raeburn  13543: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13544: 	my $response=$ua->request($request);
1.979     raeburn  13545:         delete($alldns{$dns});
1.852     albertel 13546: 	next if ($response->is_error());
                   13547: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13548:         unless ($nocache) {
1.1172.2.23  raeburn  13549: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13550:         }
                   13551: 	&$func(\@content,$hashref);
1.869     albertel 13552: 	return;
1.852     albertel 13553:     }
1.871     albertel 13554:     my $which = (split('/',$url))[3];
                   13555:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13556:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13557:         my @content = <$config>;
                   13558:         &$func(\@content,$hashref);
                   13559:     }
1.1172.2.17  raeburn  13560:     return;
                   13561: }
                   13562: 
                   13563: # ------------------------------------------------------Get DNS checksums file
                   13564: sub parse_dns_checksums_tab {
                   13565:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13566:     my $lonhost = $perlvar{'lonHostID'};
                   13567:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13568:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13569:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13570:     my $webconfdir = '/etc/httpd/conf';
                   13571:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13572:         $webconfdir = '/etc/apache2';
                   13573:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13574:         if ($1 >= 10) {
                   13575:             $webconfdir = '/etc/apache2';
                   13576:         }
                   13577:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13578:         if ($1 >= 10.0) {
                   13579:             $webconfdir = '/etc/apache2';
                   13580:         }
                   13581:     }
1.1172.2.17  raeburn  13582:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13583:     my (%chksum,%revnum);
                   13584:     if (ref($lines) eq 'ARRAY') {
                   13585:         chomp(@{$lines});
1.1172.2.34  raeburn  13586:         my $version = shift(@{$lines});
                   13587:         if ($version eq $release) {
1.1172.2.17  raeburn  13588:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13589:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13590:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13591:                     if ($webconfdir eq '/etc/apache2') {
                   13592:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13593:                     }
                   13594:                 }
1.1172.2.34  raeburn  13595:                 $chksum{$file} = $shasum;
                   13596:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13597:             }
                   13598:             if (ref($hashref) eq 'HASH') {
                   13599:                 %{$hashref} = (
                   13600:                                 sums     => \%chksum,
                   13601:                                 versions => \%revnum,
                   13602:                               );
                   13603:             }
                   13604:         }
                   13605:     }
1.869     albertel 13606:     return;
1.852     albertel 13607: }
1.1172.2.17  raeburn  13608: 
                   13609: sub fetch_dns_checksums {
                   13610:     my %checksums;
1.1172.2.34  raeburn  13611:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13612:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13613:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13614:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13615:              \%checksums);
                   13616:     return \%checksums;
                   13617: }
                   13618: 
1.327     albertel 13619: # ------------------------------------------------------------ Read domain file
                   13620: {
1.852     albertel 13621:     my $loaded;
1.846     albertel 13622:     my %domain;
                   13623: 
1.852     albertel 13624:     sub parse_domain_tab {
                   13625: 	my ($lines) = @_;
                   13626: 	foreach my $line (@$lines) {
                   13627: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13628: 
1.846     albertel 13629: 	    chomp($line);
1.852     albertel 13630: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13631: 	    my %this_domain;
                   13632: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13633: 			       'lang_def', 'city', 'longi', 'lati',
                   13634: 			       'primary') {
                   13635: 		$this_domain{$field} = shift(@elements);
                   13636: 	    }
                   13637: 	    $domain{$name} = \%this_domain;
1.852     albertel 13638: 	}
                   13639:     }
1.864     albertel 13640: 
                   13641:     sub reset_domain_info {
                   13642: 	undef($loaded);
                   13643: 	undef(%domain);
                   13644:     }
                   13645: 
1.852     albertel 13646:     sub load_domain_tab {
1.1172.2.70  raeburn  13647: 	my ($ignore_cache,$nocache) = @_;
                   13648: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13649: 	my $fh;
1.1172.2.96  raeburn  13650: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13651: 	    my @lines = <$fh>;
                   13652: 	    &parse_domain_tab(\@lines);
1.448     albertel 13653: 	}
1.852     albertel 13654: 	close($fh);
                   13655: 	$loaded = 1;
1.327     albertel 13656:     }
1.846     albertel 13657: 
                   13658:     sub domain {
1.852     albertel 13659: 	&load_domain_tab() if (!$loaded);
                   13660: 
1.846     albertel 13661: 	my ($name,$what) = @_;
                   13662: 	return if ( !exists($domain{$name}) );
                   13663: 
                   13664: 	if (!$what) {
                   13665: 	    return $domain{$name}{'description'};
                   13666: 	}
                   13667: 	return $domain{$name}{$what};
                   13668:     }
1.974     raeburn  13669: 
                   13670:     sub domain_info {
                   13671:         &load_domain_tab() if (!$loaded);
                   13672:         return %domain;
                   13673:     }
                   13674: 
1.327     albertel 13675: }
                   13676: 
                   13677: 
1.1       albertel 13678: # ------------------------------------------------------------- Read hosts file
                   13679: {
1.838     albertel 13680:     my %hostname;
1.844     albertel 13681:     my %hostdom;
1.845     albertel 13682:     my %libserv;
1.852     albertel 13683:     my $loaded;
1.888     albertel 13684:     my %name_to_host;
1.1074    raeburn  13685:     my %internetdom;
1.1107    raeburn  13686:     my %LC_dns_serv;
1.852     albertel 13687: 
                   13688:     sub parse_hosts_tab {
                   13689: 	my ($file) = @_;
                   13690: 	foreach my $configline (@$file) {
                   13691: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13692:             chomp($configline);
                   13693: 	    if ($configline =~ /^\^/) {
                   13694:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13695:                     $LC_dns_serv{$1} = 1;
                   13696:                 }
                   13697:                 next;
                   13698:             }
1.1074    raeburn  13699: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13700: 	    $name=~s/\s//g;
                   13701: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13702:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13703:                     my $curr = $hostname{$id};
                   13704:                     my $skip;
                   13705:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13706:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13707:                             $skip = 1;
                   13708:                         } else {
                   13709:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13710:                         }
                   13711:                     }
                   13712:                     unless ($skip) {
                   13713:                         push(@{$name_to_host{$name}},$id);
                   13714:                     }
                   13715:                 } else {
                   13716:                     push(@{$name_to_host{$name}},$id);
                   13717:                 }
1.852     albertel 13718: 		$hostname{$id}=$name;
                   13719: 		$hostdom{$id}=$domain;
                   13720: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13721:                 if (defined($protocol)) {
                   13722:                     if ($protocol eq 'https') {
                   13723:                         $protocol{$id} = $protocol;
                   13724:                     } else {
                   13725:                         $protocol{$id} = 'http'; 
                   13726:                     }
1.968     raeburn  13727:                 } else {
1.969     raeburn  13728:                     $protocol{$id} = 'http';
1.968     raeburn  13729:                 }
1.1074    raeburn  13730:                 if (defined($intdom)) {
                   13731:                     $internetdom{$id} = $intdom;
                   13732:                 }
1.852     albertel 13733: 	    }
                   13734: 	}
                   13735:     }
1.864     albertel 13736:     
                   13737:     sub reset_hosts_info {
1.897     albertel 13738: 	&purge_remembered();
1.864     albertel 13739: 	&reset_domain_info();
                   13740: 	&reset_hosts_ip_info();
1.892     albertel 13741: 	undef(%name_to_host);
1.864     albertel 13742: 	undef(%hostname);
                   13743: 	undef(%hostdom);
                   13744: 	undef(%libserv);
                   13745: 	undef($loaded);
                   13746:     }
1.1       albertel 13747: 
1.852     albertel 13748:     sub load_hosts_tab {
1.1172.2.70  raeburn  13749: 	my ($ignore_cache,$nocache) = @_;
                   13750: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13751: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13752: 	my @config = <$config>;
                   13753: 	&parse_hosts_tab(\@config);
                   13754: 	close($config);
                   13755: 	$loaded=1;
1.1       albertel 13756:     }
1.852     albertel 13757: 
1.838     albertel 13758:     sub hostname {
1.852     albertel 13759: 	&load_hosts_tab() if (!$loaded);
                   13760: 
1.838     albertel 13761: 	my ($lonid) = @_;
                   13762: 	return $hostname{$lonid};
                   13763:     }
1.845     albertel 13764: 
1.838     albertel 13765:     sub all_hostnames {
1.852     albertel 13766: 	&load_hosts_tab() if (!$loaded);
                   13767: 
1.838     albertel 13768: 	return %hostname;
                   13769:     }
1.845     albertel 13770: 
1.888     albertel 13771:     sub all_names {
1.1172.2.70  raeburn  13772:         my ($ignore_cache,$nocache) = @_;
                   13773: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13774: 
                   13775: 	return %name_to_host;
                   13776:     }
                   13777: 
1.974     raeburn  13778:     sub all_host_domain {
                   13779:         &load_hosts_tab() if (!$loaded);
                   13780:         return %hostdom;
                   13781:     }
                   13782: 
1.845     albertel 13783:     sub is_library {
1.852     albertel 13784: 	&load_hosts_tab() if (!$loaded);
                   13785: 
1.845     albertel 13786: 	return exists($libserv{$_[0]});
                   13787:     }
                   13788: 
                   13789:     sub all_library {
1.852     albertel 13790: 	&load_hosts_tab() if (!$loaded);
                   13791: 
1.845     albertel 13792: 	return %libserv;
                   13793:     }
                   13794: 
1.1062    droeschl 13795:     sub unique_library {
                   13796: 	#2x reverse removes all hostnames that appear more than once
                   13797:         my %unique = reverse &all_library();
                   13798:         return reverse %unique;
                   13799:     }
                   13800: 
1.841     albertel 13801:     sub get_servers {
1.852     albertel 13802: 	&load_hosts_tab() if (!$loaded);
                   13803: 
1.841     albertel 13804: 	my ($domain,$type) = @_;
                   13805: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13806: 	                                          : %hostname;
                   13807: 	my %result;
1.842     albertel 13808: 	if (ref($domain) eq 'ARRAY') {
                   13809: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13810: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13811: 		    $result{$host} = $hostname;
                   13812: 		}
                   13813: 	    }
                   13814: 	} else {
                   13815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13816: 		if ($hostdom{$host} eq $domain) {
                   13817: 		    $result{$host} = $hostname;
                   13818: 		}
1.841     albertel 13819: 	    }
                   13820: 	}
                   13821: 	return %result;
                   13822:     }
1.845     albertel 13823: 
1.1062    droeschl 13824:     sub get_unique_servers {
                   13825:         my %unique = reverse &get_servers(@_);
                   13826: 	return reverse %unique;
                   13827:     }
                   13828: 
1.844     albertel 13829:     sub host_domain {
1.852     albertel 13830: 	&load_hosts_tab() if (!$loaded);
                   13831: 
1.844     albertel 13832: 	my ($lonid) = @_;
                   13833: 	return $hostdom{$lonid};
                   13834:     }
                   13835: 
1.841     albertel 13836:     sub all_domains {
1.852     albertel 13837: 	&load_hosts_tab() if (!$loaded);
                   13838: 
1.841     albertel 13839: 	my %seen;
                   13840: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13841: 	return @uniq;
                   13842:     }
1.1074    raeburn  13843: 
                   13844:     sub internet_dom {
                   13845:         &load_hosts_tab() if (!$loaded);
                   13846: 
                   13847:         my ($lonid) = @_;
                   13848:         return $internetdom{$lonid};
                   13849:     }
1.1107    raeburn  13850: 
                   13851:     sub is_LC_dns {
                   13852:         &load_hosts_tab() if (!$loaded);
                   13853: 
                   13854:         my ($hostname) = @_;
                   13855:         return exists($LC_dns_serv{$hostname});
                   13856:     }
                   13857: 
1.1       albertel 13858: }
                   13859: 
1.847     albertel 13860: { 
                   13861:     my %iphost;
1.856     albertel 13862:     my %name_to_ip;
                   13863:     my %lonid_to_ip;
1.869     albertel 13864: 
1.847     albertel 13865:     sub get_hosts_from_ip {
                   13866: 	my ($ip) = @_;
                   13867: 	my %iphosts = &get_iphost();
                   13868: 	if (ref($iphosts{$ip})) {
                   13869: 	    return @{$iphosts{$ip}};
                   13870: 	}
                   13871: 	return;
1.839     albertel 13872:     }
1.864     albertel 13873:     
                   13874:     sub reset_hosts_ip_info {
                   13875: 	undef(%iphost);
                   13876: 	undef(%name_to_ip);
                   13877: 	undef(%lonid_to_ip);
                   13878:     }
1.856     albertel 13879: 
                   13880:     sub get_host_ip {
                   13881: 	my ($lonid) = @_;
                   13882: 	if (exists($lonid_to_ip{$lonid})) {
                   13883: 	    return $lonid_to_ip{$lonid};
                   13884: 	}
                   13885: 	my $name=&hostname($lonid);
                   13886:    	my $ip = gethostbyname($name);
                   13887: 	return if (!$ip || length($ip) ne 4);
                   13888: 	$ip=inet_ntoa($ip);
                   13889: 	$name_to_ip{$name}   = $ip;
                   13890: 	$lonid_to_ip{$lonid} = $ip;
                   13891: 	return $ip;
                   13892:     }
1.847     albertel 13893:     
                   13894:     sub get_iphost {
1.1172.2.70  raeburn  13895: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13896: 
1.869     albertel 13897: 	if (!$ignore_cache) {
                   13898: 	    if (%iphost) {
                   13899: 		return %iphost;
                   13900: 	    }
                   13901: 	    my ($ip_info,$cached)=
                   13902: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13903: 	    if ($cached) {
                   13904: 		%iphost      = %{$ip_info->[0]};
                   13905: 		%name_to_ip  = %{$ip_info->[1]};
                   13906: 		%lonid_to_ip = %{$ip_info->[2]};
                   13907: 		return %iphost;
                   13908: 	    }
                   13909: 	}
1.894     albertel 13910: 
                   13911: 	# get yesterday's info for fallback
                   13912: 	my %old_name_to_ip;
                   13913: 	my ($ip_info,$cached)=
                   13914: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13915: 	if ($cached) {
                   13916: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13917: 	}
                   13918: 
1.1172.2.70  raeburn  13919: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13920: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13921: 	    my $ip;
                   13922: 	    if (!exists($name_to_ip{$name})) {
                   13923: 		$ip = gethostbyname($name);
                   13924: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13925: 		    if (defined($old_name_to_ip{$name})) {
                   13926: 			$ip = $old_name_to_ip{$name};
                   13927: 			&logthis("Can't find $name defaulting to old $ip");
                   13928: 		    } else {
                   13929: 			&logthis("Name $name no IP found");
                   13930: 			next;
                   13931: 		    }
                   13932: 		} else {
                   13933: 		    $ip=inet_ntoa($ip);
1.847     albertel 13934: 		}
                   13935: 		$name_to_ip{$name} = $ip;
                   13936: 	    } else {
                   13937: 		$ip = $name_to_ip{$name};
1.653     albertel 13938: 	    }
1.888     albertel 13939: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13940: 		$lonid_to_ip{$id} = $ip;
                   13941: 	    }
                   13942: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13943: 	}
1.1172.2.70  raeburn  13944:         unless ($nocache) {
                   13945: 	    &do_cache_new('iphost','iphost',
                   13946: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13947: 		          48*60*60);
                   13948:         }
1.869     albertel 13949: 
1.847     albertel 13950: 	return %iphost;
1.598     albertel 13951:     }
                   13952: 
1.992     raeburn  13953:     #
                   13954:     #  Given a DNS returns the loncapa host name for that DNS 
                   13955:     # 
                   13956:     sub host_from_dns {
                   13957:         my ($dns) = @_;
                   13958:         my @hosts;
                   13959:         my $ip;
                   13960: 
1.993     raeburn  13961:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13962:             $ip = $name_to_ip{$dns};
                   13963:         }
                   13964:         if (!$ip) {
                   13965:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13966:             if (length($ip) == 4) { 
                   13967: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13968:             }
                   13969:         }
                   13970:         if ($ip) {
                   13971: 	    @hosts = get_hosts_from_ip($ip);
                   13972: 	    return $hosts[0];
                   13973:         }
                   13974:         return undef;
1.986     foxr     13975:     }
1.992     raeburn  13976: 
1.1074    raeburn  13977:     sub get_internet_names {
                   13978:         my ($lonid) = @_;
                   13979:         return if ($lonid eq '');
                   13980:         my ($idnref,$cached)=
                   13981:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13982:         if ($cached) {
                   13983:             return $idnref;
                   13984:         }
                   13985:         my $ip = &get_host_ip($lonid);
                   13986:         my @hosts = &get_hosts_from_ip($ip);
                   13987:         my %iphost = &get_iphost();
                   13988:         my (@idns,%seen);
                   13989:         foreach my $id (@hosts) {
                   13990:             my $dom = &host_domain($id);
                   13991:             my $prim_id = &domain($dom,'primary');
                   13992:             my $prim_ip = &get_host_ip($prim_id);
                   13993:             next if ($seen{$prim_ip});
                   13994:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13995:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13996:                     my $intdom = &internet_dom($id);
                   13997:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13998:                         push(@idns,$intdom);
                   13999:                     }
                   14000:                 }
                   14001:             }
                   14002:             $seen{$prim_ip} = 1;
                   14003:         }
1.1172.2.23  raeburn  14004:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14005:     }
                   14006: 
1.986     foxr     14007: }
                   14008: 
1.1079    raeburn  14009: sub all_loncaparevs {
1.1172.2.39  raeburn  14010:     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  14011: }
                   14012: 
1.1172.2.27  raeburn  14013: # ------------------------------------------------------- Read loncaparev table
                   14014: {
                   14015:     sub load_loncaparevs {
                   14016:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14017:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14018:                 while (my $configline=<$config>) {
                   14019:                     chomp($configline);
                   14020:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14021:                     $loncaparevs{$hostid}=$loncaparev;
                   14022:                 }
                   14023:                 close($config);
                   14024:             }
                   14025:         }
                   14026:     }
                   14027: }
                   14028: 
                   14029: # ----------------------------------------------------- Read serverhostID table
                   14030: {
                   14031:     sub load_serverhomeIDs {
                   14032:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14033:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14034:                 while (my $configline=<$config>) {
                   14035:                     chomp($configline);
                   14036:                     my ($name,$id)=split(/:/,$configline);
                   14037:                     $serverhomeIDs{$name}=$id;
                   14038:                 }
                   14039:                 close($config);
                   14040:             }
                   14041:         }
                   14042:     }
                   14043: }
                   14044: 
                   14045: 
1.862     albertel 14046: BEGIN {
                   14047: 
                   14048: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14049:     unless ($readit) {
                   14050: {
                   14051:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14052:     %perlvar = (%perlvar,%{$configvars});
                   14053: }
                   14054: 
                   14055: 
1.1       albertel 14056: # ------------------------------------------------------ Read spare server file
                   14057: {
1.1172.2.96  raeburn  14058:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14059: 
                   14060:     while (my $configline=<$config>) {
                   14061:        chomp($configline);
1.284     matthew  14062:        if ($configline) {
1.784     albertel 14063: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14064: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14065: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14066:        }
                   14067:     }
1.448     albertel 14068:     close($config);
1.1       albertel 14069: }
1.11      www      14070: # ------------------------------------------------------------ Read permissions
                   14071: {
1.1172.2.96  raeburn  14072:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14073: 
                   14074:     while (my $configline=<$config>) {
1.448     albertel 14075: 	chomp($configline);
                   14076: 	if ($configline) {
                   14077: 	    my ($role,$perm)=split(/ /,$configline);
                   14078: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14079: 	}
1.11      www      14080:     }
1.448     albertel 14081:     close($config);
1.11      www      14082: }
                   14083: 
                   14084: # -------------------------------------------- Read plain texts for permissions
                   14085: {
1.1172.2.96  raeburn  14086:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14087: 
                   14088:     while (my $configline=<$config>) {
1.448     albertel 14089: 	chomp($configline);
                   14090: 	if ($configline) {
1.742     raeburn  14091: 	    my ($short,@plain)=split(/:/,$configline);
                   14092:             %{$prp{$short}} = ();
                   14093: 	    if (@plain > 0) {
                   14094:                 $prp{$short}{'std'} = $plain[0];
                   14095:                 for (my $i=1; $i<@plain; $i++) {
                   14096:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14097:                 }
                   14098:             }
1.448     albertel 14099: 	}
1.135     www      14100:     }
1.448     albertel 14101:     close($config);
1.135     www      14102: }
                   14103: 
                   14104: # ---------------------------------------------------------- Read package table
                   14105: {
1.1172.2.96  raeburn  14106:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14107: 
                   14108:     while (my $configline=<$config>) {
1.483     albertel 14109: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14110: 	chomp($configline);
                   14111: 	my ($short,$plain)=split(/:/,$configline);
                   14112: 	my ($pack,$name)=split(/\&/,$short);
                   14113: 	if ($plain ne '') {
                   14114: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14115: 	    $packagetab{$short}=$plain; 
                   14116: 	}
1.11      www      14117:     }
1.448     albertel 14118:     close($config);
1.329     matthew  14119: }
                   14120: 
1.1172.2.27  raeburn  14121: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14122: 
1.1172.2.27  raeburn  14123: &load_loncaparevs();
                   14124: 
                   14125: # ------------------------------------------------------- Read serverhostID table
                   14126: 
                   14127: &load_serverhomeIDs();
1.1074    raeburn  14128: 
1.1172.2.27  raeburn  14129: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14130: {
                   14131:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14132:     if (-e $file) {
                   14133:         my $parser = HTML::LCParser->new($file);
                   14134:         while (my $token = $parser->get_token()) {
                   14135:             if ($token->[0] eq 'S') {
                   14136:                 my $item = $token->[1];
                   14137:                 my $name = $token->[2]{'name'};
                   14138:                 my $value = $token->[2]{'value'};
                   14139:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14140:                     my $release = $parser->get_text();
                   14141:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14142:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14143:                 }
                   14144:             }
                   14145:         }
                   14146:     }
1.1073    raeburn  14147: }
                   14148: 
1.1138    raeburn  14149: # ---------------------------------------------------------- Read managers table
                   14150: {
                   14151:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14152:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14153:             while (my $configline=<$config>) {
                   14154:                 chomp($configline);
                   14155:                 next if ($configline =~ /^\#/);
                   14156:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14157:                     $managerstab{$configline} = 1;
                   14158:                 }
                   14159:             }
                   14160:             close($config);
                   14161:         }
                   14162:     }
                   14163: }
                   14164: 
1.329     matthew  14165: # ------------- set up temporary directory
                   14166: {
1.1117    foxr     14167:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14168: 
1.11      www      14169: }
                   14170: 
1.1172.2.104  raeburn  14171: # ------------- set default texengine (domain default overrides this)
                   14172: {
                   14173:     $deftex = LONCAPA::texengine();
                   14174: }
                   14175: 
1.1172.2.114  raeburn  14176: # ------------- set default minimum length for passwords for internal auth users
                   14177: {
                   14178:     $passwdmin = LONCAPA::passwd_min();
                   14179: }
                   14180: 
1.794     albertel 14181: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14182: 				'compress_threshold'=> 20_000,
                   14183:  			        });
1.185     www      14184: 
1.281     www      14185: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14186: $dumpcount=0;
1.958     www      14187: $locknum=0;
1.22      www      14188: 
1.163     harris41 14189: &logtouch();
1.672     albertel 14190: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14191: $readit=1;
1.564     albertel 14192:     {
                   14193: 	use integer;
                   14194: 	my $test=(2**32)+1;
1.568     albertel 14195: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14196: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14197:     }
1.195     www      14198: }
1.1       albertel 14199: }
1.179     www      14200: 
1.1       albertel 14201: 1;
1.191     harris41 14202: __END__
                   14203: 
1.243     albertel 14204: =pod
                   14205: 
1.191     harris41 14206: =head1 NAME
                   14207: 
1.243     albertel 14208: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14209: 
                   14210: =head1 SYNOPSIS
                   14211: 
1.243     albertel 14212: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14213: 
                   14214:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14215: 
1.243     albertel 14216: Common parameters:
                   14217: 
                   14218: =over 4
                   14219: 
                   14220: =item *
                   14221: 
                   14222: $uname : an internal username (if $cname expecting a course Id specifically)
                   14223: 
                   14224: =item *
                   14225: 
                   14226: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14227: 
                   14228: =item *
                   14229: 
                   14230: $symb : a resource instance identifier
                   14231: 
                   14232: =item *
                   14233: 
                   14234: $namespace : the name of a .db file that contains the data needed or
                   14235: being set.
                   14236: 
                   14237: =back
                   14238: 
1.394     bowersj2 14239: =head1 OVERVIEW
1.191     harris41 14240: 
1.394     bowersj2 14241: lonnet provides subroutines which interact with the
                   14242: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14243: about classes, users, and resources.
1.243     albertel 14244: 
                   14245: For many of these objects you can also use this to store data about
                   14246: them or modify them in various ways.
1.191     harris41 14247: 
1.394     bowersj2 14248: =head2 Symbs
1.191     harris41 14249: 
1.394     bowersj2 14250: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14251: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14252: map, the resource number of the resource in the map, and the URL of
                   14253: the resource itself. The latter is somewhat redundant, but might help
                   14254: if maps change.
                   14255: 
                   14256: An example is
                   14257: 
                   14258:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14259: 
                   14260: The respective map entry is
                   14261: 
                   14262:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14263:   title="Problem 2">
                   14264:  </resource>
                   14265: 
                   14266: Symbs are used by the random number generator, as well as to store and
                   14267: restore data specific to a certain instance of for example a problem.
                   14268: 
                   14269: =head2 Storing And Retrieving Data
                   14270: 
                   14271: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14272: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14273: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14274: is is the non-critical message twin of cstore. These functions are for
                   14275: handlers to store a perl hash to a user's permanent data space in an
                   14276: easy manner, and to retrieve it again on another call. It is expected
                   14277: that a handler would use this once at the beginning to retrieve data,
                   14278: and then again once at the end to send only the new data back.
                   14279: 
                   14280: The data is stored in the user's data directory on the user's
                   14281: homeserver under the ID of the course.
                   14282: 
                   14283: The hash that is returned by restore will have all of the previous
                   14284: value for all of the elements of the hash.
                   14285: 
                   14286: Example:
                   14287: 
                   14288:  #creating a hash
                   14289:  my %hash;
                   14290:  $hash{'foo'}='bar';
                   14291: 
                   14292:  #storing it
                   14293:  &Apache::lonnet::cstore(\%hash);
                   14294: 
                   14295:  #changing a value
                   14296:  $hash{'foo'}='notbar';
                   14297: 
                   14298:  #adding a new value
                   14299:  $hash{'bar'}='foo';
                   14300:  &Apache::lonnet::cstore(\%hash);
                   14301: 
                   14302:  #retrieving the hash
                   14303:  my %history=&Apache::lonnet::restore();
                   14304: 
                   14305:  #print the hash
                   14306:  foreach my $key (sort(keys(%history))) {
                   14307:    print("\%history{$key} = $history{$key}");
                   14308:  }
                   14309: 
                   14310: Will print out:
1.191     harris41 14311: 
1.394     bowersj2 14312:  %history{1:foo} = bar
                   14313:  %history{1:keys} = foo:timestamp
                   14314:  %history{1:timestamp} = 990455579
                   14315:  %history{2:bar} = foo
                   14316:  %history{2:foo} = notbar
                   14317:  %history{2:keys} = foo:bar:timestamp
                   14318:  %history{2:timestamp} = 990455580
                   14319:  %history{bar} = foo
                   14320:  %history{foo} = notbar
                   14321:  %history{timestamp} = 990455580
                   14322:  %history{version} = 2
                   14323: 
                   14324: Note that the special hash entries C<keys>, C<version> and
                   14325: C<timestamp> were added to the hash. C<version> will be equal to the
                   14326: total number of versions of the data that have been stored. The
                   14327: C<timestamp> attribute will be the UNIX time the hash was
                   14328: stored. C<keys> is available in every historical section to list which
                   14329: keys were added or changed at a specific historical revision of a
                   14330: hash.
                   14331: 
                   14332: B<Warning>: do not store the hash that restore returns directly. This
                   14333: will cause a mess since it will restore the historical keys as if the
                   14334: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14335: 
1.394     bowersj2 14336: Calling convention:
1.191     harris41 14337: 
1.1172.2.27  raeburn  14338:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14339:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14340: 
1.394     bowersj2 14341: For more detailed information, see lonnet specific documentation.
1.191     harris41 14342: 
1.394     bowersj2 14343: =head1 RETURN MESSAGES
1.191     harris41 14344: 
1.394     bowersj2 14345: =over 4
1.191     harris41 14346: 
1.394     bowersj2 14347: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14348: 
1.394     bowersj2 14349: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14350: when the connection is brought back up
1.191     harris41 14351: 
1.394     bowersj2 14352: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14353: for later delivery
1.191     harris41 14354: 
1.967     bisitz   14355: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14356: 
1.394     bowersj2 14357: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14358: that was requested
1.191     harris41 14359: 
1.243     albertel 14360: =back
1.191     harris41 14361: 
1.243     albertel 14362: =head1 PUBLIC SUBROUTINES
1.191     harris41 14363: 
1.243     albertel 14364: =head2 Session Environment Functions
1.191     harris41 14365: 
1.243     albertel 14366: =over 4
1.191     harris41 14367: 
1.394     bowersj2 14368: =item * 
                   14369: X<appenv()>
1.949     raeburn  14370: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14371: the user envirnoment file, and will be restored for each access this
1.620     albertel 14372: user makes during this session, also modifies the %env for the current
1.949     raeburn  14373: process. Optional rolesarrayref - if defined contains a reference to an array
                   14374: of roles which are exempt from the restriction on modifying user.role entries 
                   14375: in the user's environment.db and in %env.    
1.191     harris41 14376: 
                   14377: =item *
1.394     bowersj2 14378: X<delenv()>
1.987     raeburn  14379: B<delenv($delthis,$regexp)>: removes all items from the session
                   14380: environment file that begin with $delthis. If the 
                   14381: optional second arg - $regexp - is true, $delthis is treated as a 
                   14382: regular expression, otherwise \Q$delthis\E is used. 
                   14383: The values are also deleted from the current processes %env.
1.191     harris41 14384: 
1.795     albertel 14385: =item * get_env_multiple($name) 
                   14386: 
                   14387: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14388: values may be defined and end up as an array ref.
                   14389: 
                   14390: returns an array of values
                   14391: 
1.243     albertel 14392: =back
                   14393: 
                   14394: =head2 User Information
1.191     harris41 14395: 
1.243     albertel 14396: =over 4
1.191     harris41 14397: 
                   14398: =item *
1.394     bowersj2 14399: X<queryauthenticate()>
                   14400: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14401: authentication scheme
                   14402: 
                   14403: =item *
1.394     bowersj2 14404: X<authenticate()>
1.1073    raeburn  14405: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14406: authenticate user from domain's lib servers (first use the current
                   14407: one). C<$upass> should be the users password.
1.1073    raeburn  14408: $checkdefauth is optional (value is 1 if a check should be made to
                   14409:    authenticate user using default authentication method, and allow
                   14410:    account creation if username does not have account in the domain).
                   14411: $clientcancheckhost is optional (value is 1 if checking whether the
                   14412:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14413: 
                   14414: =item *
1.394     bowersj2 14415: X<homeserver()>
                   14416: B<homeserver($uname,$udom)>: find the server which has
                   14417: the user's directory and files (there must be only one), this caches
                   14418: the answer, and also caches if there is a borken connection.
1.191     harris41 14419: 
                   14420: =item *
1.394     bowersj2 14421: X<idget()>
                   14422: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14423: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14424: username, and only 1 username per ID in a specific domain) (returns
                   14425: hash: id=>name,id=>name)
1.191     harris41 14426: 
                   14427: =item *
1.394     bowersj2 14428: X<idrget()>
                   14429: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14430: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14431: 
                   14432: =item *
1.394     bowersj2 14433: X<idput()>
                   14434: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14435: 
                   14436: =item *
1.394     bowersj2 14437: X<rolesinit()>
1.1169    droeschl 14438: B<rolesinit($udom,$username)>: get user privileges.
                   14439: returns user role, first access and timer interval hashes
1.243     albertel 14440: 
                   14441: =item *
1.1171    droeschl 14442: X<privileged()>
                   14443: B<privileged($username,$domain)>: returns a true if user has a
                   14444: privileged and active role (i.e. su or dc), false otherwise.
                   14445: 
                   14446: =item *
1.551     albertel 14447: X<getsection()>
                   14448: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14449: course $cname, return section name/number or '' for "not in course"
                   14450: and '-1' for "no section"
                   14451: 
                   14452: =item *
1.394     bowersj2 14453: X<userenvironment()>
                   14454: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14455: passed in @what from the requested user's environment, returns a hash
                   14456: 
1.858     raeburn  14457: =item * 
                   14458: X<userlog_query()>
1.859     albertel 14459: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14460: activity.log file. %filters defines filters applied when parsing the
                   14461: log file. These can be start or end timestamps, or the type of action
                   14462: - log to look for Login or Logout events, check for Checkin or
                   14463: Checkout, role for role selection. The response is in the form
                   14464: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14465: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14466: 
1.243     albertel 14467: =back
                   14468: 
                   14469: =head2 User Roles
                   14470: 
                   14471: =over 4
                   14472: 
                   14473: =item *
                   14474: 
1.1172.2.65  raeburn  14475: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14476: returns codes for allowed actions.
                   14477: 
                   14478: The first argument is required, all others are optional.
                   14479: 
                   14480: $priv is the privilege being checked.
                   14481: $uri contains additional information about what is being checked for access (e.g.,
                   14482: URL, course ID etc.).
                   14483: $symb is the unique resource instance identifier in a course; if needed,
                   14484: but not provided, it will be retrieved via a call to &symbread().
                   14485: $role is the role for which a priv is being checked (only used if priv is evb).
                   14486: $clientip is the user's IP address (only used when checking for access to portfolio
                   14487: files).
                   14488: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14489: prevents recursive calls to &allowed.
                   14490: 
1.243     albertel 14491:  F: full access
                   14492:  U,I,K: authentication modes (cxx only)
                   14493:  '': forbidden
                   14494:  1: user needs to choose course
                   14495:  2: browse allowed
1.766     albertel 14496:  A: passphrase authentication needed
1.1172.2.65  raeburn  14497:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14498: 
                   14499: =item *
                   14500: 
1.1172.2.13  raeburn  14501: constructaccess($url,$setpriv) : check for access to construction space URL
                   14502: 
                   14503: See if the owner domain and name in the URL match those in the
                   14504: expected environment.  If so, return three element list
                   14505: ($ownername,$ownerdomain,$ownerhome).
                   14506: 
                   14507: Otherwise return the null string.
                   14508: 
                   14509: If second argument 'setpriv' is true, it assigns the privileges,
                   14510: and returns the same three element list, unless the owner has
                   14511: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14512: in which case the null string is returned.
                   14513: 
                   14514: =item *
                   14515: 
1.1172.2.84  raeburn  14516: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14517: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14518: for system, domain, and course level. $uname and $udom are optional (current
                   14519: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14520: 
                   14521: =item *
                   14522: 
1.988     raeburn  14523: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14524: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14525: $type is Course (default) or Community.
1.988     raeburn  14526: If $forcedefault evaluates to true, text returned will be default 
                   14527: text for $type. Otherwise, if this is a course, the text returned 
                   14528: will be a custom name for the role (if defined in the course's 
                   14529: environment).  If no custom name is defined the default is returned.
                   14530:    
1.832     raeburn  14531: =item *
                   14532: 
1.1172.2.23  raeburn  14533: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14534: All arguments are optional. Returns a hash of a roles, either for
                   14535: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14536: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14537: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14538: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14539: For each key, value is set to colon-separated start and end times for
                   14540: the role.  If no username and domain are specified, will default to
1.934     raeburn  14541: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14542: of role statuses (active, future or previous), roles 
                   14543: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14544: to restrict the list of roles reported. If no array ref is 
                   14545: provided for types, will default to return only active roles.
1.834     albertel 14546: 
1.1172.2.13  raeburn  14547: =item *
                   14548: 
                   14549: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14550: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14551: 
                   14552: Additional optional arguments are: $type (if role checking is to be restricted
                   14553: to certain user status types -- previous (expired roles), active (currently
                   14554: available roles) or future (roles available in the future), and
                   14555: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14556: have active Domain Coordinator role in course's domain or in additional
                   14557: domains (specified in 'Domains to check for privileged users' in course
                   14558: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14559: 
                   14560: =item *
                   14561: 
                   14562: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14563: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14564: $possdomains and $possroles are optional array refs -- to domains to check and
                   14565: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14566: users' roles.db to check for a dc or su role in any domain. This can be
                   14567: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14568: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14569: this then allows &privileged_by_domain() to be used, which caches the identity
                   14570: of privileged users, eliminating the need for repeated calls to &dump().
                   14571: 
                   14572: =item *
                   14573: 
                   14574: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14575: where the outer hash keys are domains specified in the $possdomains array ref,
                   14576: next inner hash keys are privileged roles specified in the $roles array ref,
                   14577: and the innermost hash contains key = value pairs for username:domain = end:start
                   14578: for active or future "privileged" users with that role in that domain. To avoid
                   14579: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14580: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14581: 
1.243     albertel 14582: =back
                   14583: 
                   14584: =head2 User Modification
                   14585: 
                   14586: =over 4
                   14587: 
                   14588: =item *
                   14589: 
1.957     raeburn  14590: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14591: user for the level given by URL.  Optional start and end dates (leave empty
                   14592: string or zero for "no date")
1.191     harris41 14593: 
                   14594: =item *
                   14595: 
1.243     albertel 14596: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14597: change a users, password, possible return values are: ok,
                   14598: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14599: refused
1.191     harris41 14600: 
                   14601: =item *
                   14602: 
1.243     albertel 14603: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14604: 
                   14605: =item *
                   14606: 
1.1058    raeburn  14607: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14608:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14609: 
                   14610: will update user information (firstname,middlename,lastname,generation,
                   14611: permanentemail), and if forceid is true, student/employee ID also.
                   14612: A user's institutional affiliation(s) can also be updated.
                   14613: User information fields will not be overwritten with empty entries 
                   14614: unless the field is included in the $candelete array reference.
                   14615: This array is included when a single user is modified via "Manage Users",
                   14616: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14617: 
                   14618: =item *
                   14619: 
1.286     matthew  14620: modifystudent
                   14621: 
1.957     raeburn  14622: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14623: The course id is resolved based on the current user's environment.  
                   14624: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14625: associated with a course.
                   14626: 
1.297     matthew  14627: This call is essentially a wrapper for lonnet::modifyuser and
                   14628: lonnet::modify_student_enrollment
1.286     matthew  14629: 
                   14630: Inputs: 
                   14631: 
                   14632: =over 4
                   14633: 
1.957     raeburn  14634: =item B<$udom> Student's loncapa domain
1.286     matthew  14635: 
1.957     raeburn  14636: =item B<$uname> Student's loncapa login name
1.286     matthew  14637: 
1.964     bisitz   14638: =item B<$uid> Student/Employee ID
1.286     matthew  14639: 
1.957     raeburn  14640: =item B<$umode> Student's authentication mode
1.286     matthew  14641: 
1.957     raeburn  14642: =item B<$upass> Student's password
1.286     matthew  14643: 
1.957     raeburn  14644: =item B<$first> Student's first name
1.286     matthew  14645: 
1.957     raeburn  14646: =item B<$middle> Student's middle name
1.286     matthew  14647: 
1.957     raeburn  14648: =item B<$last> Student's last name
1.286     matthew  14649: 
1.957     raeburn  14650: =item B<$gene> Student's generation
1.286     matthew  14651: 
1.957     raeburn  14652: =item B<$usec> Student's section in course
1.286     matthew  14653: 
                   14654: =item B<$end> Unix time of the roles expiration
                   14655: 
                   14656: =item B<$start> Unix time of the roles start date
                   14657: 
                   14658: =item B<$forceid> If defined, allow $uid to be changed
                   14659: 
                   14660: =item B<$desiredhome> server to use as home server for student
                   14661: 
1.957     raeburn  14662: =item B<$email> Student's permanent e-mail address
                   14663: 
                   14664: =item B<$type> Type of enrollment (auto or manual)
                   14665: 
1.963     raeburn  14666: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14667: 
                   14668: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14669: 
1.963     raeburn  14670: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14671: 
1.963     raeburn  14672: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14673: 
1.1172.2.19  raeburn  14674: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14675: 
                   14676: =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  14677: 
1.286     matthew  14678: =back
1.297     matthew  14679: 
                   14680: =item *
                   14681: 
                   14682: modify_student_enrollment
                   14683: 
1.1172.2.31  raeburn  14684: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14685: 'role.request.course' must be defined for this function to proceed.
                   14686: 
                   14687: Inputs:
                   14688: 
                   14689: =over 4
                   14690: 
1.1172.2.31  raeburn  14691: =item $udom, student's domain
1.297     matthew  14692: 
1.1172.2.31  raeburn  14693: =item $uname, student's name
1.297     matthew  14694: 
1.1172.2.31  raeburn  14695: =item $uid, student's user id
1.297     matthew  14696: 
1.1172.2.31  raeburn  14697: =item $first, student's first name
1.297     matthew  14698: 
                   14699: =item $middle
                   14700: 
                   14701: =item $last
                   14702: 
                   14703: =item $gene
                   14704: 
                   14705: =item $usec
                   14706: 
                   14707: =item $end
                   14708: 
                   14709: =item $start
                   14710: 
1.957     raeburn  14711: =item $type
                   14712: 
                   14713: =item $locktype
                   14714: 
                   14715: =item $cid
                   14716: 
                   14717: =item $selfenroll
                   14718: 
                   14719: =item $context
                   14720: 
1.1172.2.19  raeburn  14721: =item $credits, number of credits student will earn from this class
                   14722: 
1.1172.2.76  raeburn  14723: =item $instsec, institutional course section code for student
                   14724: 
1.297     matthew  14725: =back
                   14726: 
1.191     harris41 14727: 
                   14728: =item *
                   14729: 
1.243     albertel 14730: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14731: custom role; give a custom role to a user for the level given by URL.  Specify
                   14732: name and domain of role author, and role name
1.191     harris41 14733: 
                   14734: =item *
                   14735: 
1.243     albertel 14736: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14737: 
                   14738: =item *
                   14739: 
1.243     albertel 14740: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14741: 
                   14742: =back
                   14743: 
                   14744: =head2 Course Infomation
                   14745: 
                   14746: =over 4
1.191     harris41 14747: 
                   14748: =item *
                   14749: 
1.1118    foxr     14750: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14751: specified course id, including all environment settings for the
                   14752: course, the description of the course will be in the hash under the
                   14753: key 'description'
1.191     harris41 14754: 
1.1118    foxr     14755: $options is an optional parameter that if supplied is a hash reference that controls
                   14756: what how this function works.  It has the following key/values:
                   14757: 
                   14758: =over 4
                   14759: 
                   14760: =item freshen_cache
                   14761: 
                   14762: If defined, and the environment cache for the course is valid, it is 
                   14763: returned in the returned hash.
                   14764: 
                   14765: =item one_time
                   14766: 
                   14767: If defined, the last cache time is set to _now_
                   14768: 
                   14769: =item user
                   14770: 
                   14771: If defined, the supplied username is used instead of the current user.
                   14772: 
                   14773: 
                   14774: =back
                   14775: 
1.191     harris41 14776: =item *
                   14777: 
1.624     albertel 14778: resdata($name,$domain,$type,@which) : request for current parameter
                   14779: setting for a specific $type, where $type is either 'course' or 'user',
                   14780: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14781: answers for 10 minutes.
1.243     albertel 14782: 
1.877     foxr     14783: =item *
                   14784: 
                   14785: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14786: data base, returning a hash that is keyed by the resource name and has
                   14787: values that are the resource value.  I believe that the timestamps and
                   14788: versions are also returned.
                   14789: 
1.1172.2.31  raeburn  14790: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14791: supplemental content area. This routine caches the number of files for
                   14792: 10 minutes.
                   14793: 
1.243     albertel 14794: =back
                   14795: 
                   14796: =head2 Course Modification
                   14797: 
                   14798: =over 4
1.191     harris41 14799: 
                   14800: =item *
                   14801: 
1.243     albertel 14802: writecoursepref($courseid,%prefs) : write preferences (environment
                   14803: database) for a course
1.191     harris41 14804: 
                   14805: =item *
                   14806: 
1.1011    raeburn  14807: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14808: 
                   14809: =item *
                   14810: 
1.1038    raeburn  14811: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14812: 
1.1167    droeschl 14813: =item *
                   14814: 
                   14815: is_course($courseid), is_course($cdom, $cnum)
                   14816: 
                   14817: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14818: two component version $cdom, $cnum. It checks if the specified course exists.
                   14819: 
                   14820: Returns:
                   14821:     undef if the course doesn't exist, otherwise
                   14822:     in scalar context the combined courseid.
                   14823:     in list context the two components of the course identifier, domain and 
                   14824:     courseid.    
                   14825: 
1.243     albertel 14826: =back
                   14827: 
1.1172.2.109  raeburn  14828: =head2 Bubblesheet Configuration
                   14829: 
                   14830: =over 4
                   14831: 
                   14832: =item *
                   14833: 
                   14834: get_scantron_config($which)
                   14835: 
                   14836: $which - the name of the configuration to parse from the file.
                   14837: 
                   14838: Parses and returns the bubblesheet configuration line selected as a
                   14839: hash of configuration file fields.
                   14840: 
                   14841: 
                   14842: Returns:
                   14843:     If the named configuration is not in the file, an empty
                   14844:     hash is returned.
                   14845: 
                   14846:     a hash with the fields
                   14847:       name         - internal name for the this configuration setup
                   14848:       description  - text to display to operator that describes this config
                   14849:       CODElocation - if 0 or the string 'none'
                   14850:                           - no CODE exists for this config
                   14851:                      if -1 || the string 'letter'
                   14852:                           - a CODE exists for this config and is
                   14853:                             a string of letters
                   14854:                      Unsupported value (but planned for future support)
                   14855:                           if a positive integer
                   14856:                                - The CODE exists as the first n items from
                   14857:                                  the question section of the form
                   14858:                           if the string 'number'
                   14859:                                - The CODE exists for this config and is
                   14860:                                  a string of numbers
                   14861:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14862:                      the CODE starts
                   14863:       CODElength  - length of the CODE
                   14864:       IDstart     - column where the student/employee ID starts
                   14865:       IDlength    - length of the student/employee ID info
                   14866:       Qstart      - column where the information from the bubbled
                   14867:                     'questions' start
                   14868:       Qlength     - number of columns comprising a single bubble line from
                   14869:                     the sheet. (usually either 1 or 10)
                   14870:       Qon         - either a single character representing the character used
                   14871:                     to signal a bubble was chosen in the positional setup, or
                   14872:                     the string 'letter' if the letter of the chosen bubble is
                   14873:                     in the final, or 'number' if a number representing the
                   14874:                     chosen bubble is in the file (1->A 0->J)
                   14875:       Qoff        - the character used to represent that a bubble was
                   14876:                     left blank
                   14877:       PaperID     - if the scanning process generates a unique number for each
                   14878:                     sheet scanned the column that this ID number starts in
                   14879:       PaperIDlength - number of columns that comprise the unique ID number
                   14880:                       for the sheet of paper
                   14881:       FirstName   - column that the first name starts in
                   14882:       FirstNameLength - number of columns that the first name spans
                   14883:       LastName    - column that the last name starts in
                   14884:       LastNameLength - number of columns that the last name spans
                   14885:       BubblesPerRow - number of bubbles available in each row used to
                   14886:                       bubble an answer. (If not specified, 10 assumed).
                   14887: 
                   14888: 
                   14889: =item *
                   14890: 
                   14891: get_scantronformat_file($cdom)
                   14892: 
                   14893: $cdom - the course's domain (optional); if not supplied, uses
                   14894: domain for current $env{'request.course.id'}.
                   14895: 
                   14896: Returns an array containing lines from the scantron format file for
                   14897: the domain of the course.
                   14898: 
                   14899: If a url for a custom.tab file is listed in domain's configuration.db,
                   14900: lines are from this file.
                   14901: 
                   14902: Otherwise, if a default.tab has been published in RES space by the
                   14903: domainconfig user, lines are from this file.
                   14904: 
                   14905: Otherwise, fall back to getting lines from the legacy file on the
                   14906: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14907: 
                   14908: =back
                   14909: 
1.243     albertel 14910: =head2 Resource Subroutines
                   14911: 
                   14912: =over 4
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
1.243     albertel 14916: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14917: 
                   14918: =item *
                   14919: 
1.243     albertel 14920: repcopy($filename) : subscribes to the requested file, and attempts to
                   14921: replicate from the owning library server, Might return
1.607     raeburn  14922: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14923: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14924: resource. Expects the local filesystem pathname
                   14925: (/home/httpd/html/res/....)
                   14926: 
                   14927: =back
                   14928: 
                   14929: =head2 Resource Information
                   14930: 
                   14931: =over 4
1.191     harris41 14932: 
                   14933: =item *
                   14934: 
1.1172.2.28  raeburn  14935: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14936: and returns the value of a variety of different possible values,
                   14937: $varname should be a request string, and the other parameters can be
                   14938: used to specify who and what one is asking about. Ordinarily, $cid 
                   14939: does not need to be specified, as it is retrived from 
                   14940: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14941: within lonuserstate::loadmap() when initializing a course, before
                   14942: $env{'request.course.id'} has been set, so it needs to be provided
                   14943: in that one case.
1.243     albertel 14944: 
                   14945: Possible values for $varname are environment.lastname (or other item
                   14946: from the envirnment hash), user.name (or someother aspect about the
                   14947: user), resource.0.maxtries (or some other part and parameter of a
                   14948: resource)
1.204     albertel 14949: 
                   14950: =item *
                   14951: 
1.243     albertel 14952: directcondval($number) : get current value of a condition; reads from a state
                   14953: string
1.204     albertel 14954: 
                   14955: =item *
                   14956: 
1.243     albertel 14957: condval($condidx) : value of condition index based on state
1.204     albertel 14958: 
                   14959: =item *
                   14960: 
1.243     albertel 14961: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14962: resource's metadata, $what should be either a specific key, or either
                   14963: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14964: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14965: 
                   14966: this function automatically caches all requests
1.191     harris41 14967: 
                   14968: =item *
                   14969: 
1.243     albertel 14970: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14971: network of library servers; returns file handle of where SQL and regex results
                   14972: will be stored for query
1.191     harris41 14973: 
                   14974: =item *
                   14975: 
1.1172.2.66  raeburn  14976: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14977: return symbolic list entry (all arguments optional).
                   14978: 
                   14979: Args: filename is the filename (including path) for the file for which a symb
                   14980: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14981: to check access status if more than one resource was found in the bighash
                   14982: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14983: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14984: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14985: cause possible symbs to be checked to determine if they are subject to content
                   14986: blocking, if so they will not be included as possible symbs; possibles is a
                   14987: ref to a hash, which, as a side effect, will be populated with all possible
                   14988: symbs (content blocking not tested).
                   14989: 
1.243     albertel 14990: returns the data handle
1.191     harris41 14991: 
                   14992: =item *
                   14993: 
1.1172.2.17  raeburn  14994: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14995: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14996: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14997: on failure, user must be in a course, as it assumes the existence of
                   14998: the course initial hash, and uses $env('request.course.id'}.  The third
                   14999: arg is an optional reference to a scalar.  If this arg is passed in the
                   15000: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15001: encrypted; otherwise it will be null.
1.243     albertel 15002: 
1.191     harris41 15003: =item *
                   15004: 
1.243     albertel 15005: symbclean($symb) : removes versions numbers from a symb, returns the
                   15006: cleaned symb
1.191     harris41 15007: 
                   15008: =item *
                   15009: 
1.243     albertel 15010: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15011: course map, user must be in a course for it to work.
1.191     harris41 15012: 
                   15013: =item *
                   15014: 
1.243     albertel 15015: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15016: 
                   15017: =item *
                   15018: 
1.243     albertel 15019: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15020: a random seed, all arguments are optional, if they aren't sent it uses the
                   15021: environment to derive them. Note: if symb isn't sent and it can't get one
                   15022: from &symbread it will use the current time as its return value
1.191     harris41 15023: 
                   15024: =item *
                   15025: 
1.243     albertel 15026: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15027: unfakeable, receipt
1.191     harris41 15028: 
                   15029: =item *
                   15030: 
1.620     albertel 15031: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.243     albertel 15035: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15036: 
                   15037: =item *
                   15038: 
1.243     albertel 15039: 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 15040: 
                   15041: =item *
                   15042: 
1.243     albertel 15043: 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 15044: 
                   15045: =item *
                   15046: 
1.243     albertel 15047: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15052: forcing spreadsheet to reevaluate the resource scores next time.
                   15053: 
1.1172.2.13  raeburn  15054: =item *
                   15055: 
                   15056: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15057: when viewing in course context.
                   15058: 
                   15059:  input: six args -- filename (decluttered), course number, course domain,
                   15060:                     url, symb (if registered) and group (if this is a
                   15061:                     group item -- e.g., bulletin board, group page etc.).
                   15062: 
                   15063:  output: array of five scalars --
                   15064:          $cfile -- url for file editing if editable on current server
                   15065:          $home -- homeserver of resource (i.e., for author if published,
                   15066:                                           or course if uploaded.).
                   15067:          $switchserver --  1 if server switch will be needed.
                   15068:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15069:          $forceview -- 1 if icon/link should be to go to view mode
                   15070: 
                   15071: =item *
                   15072: 
                   15073: is_course_upload($file,$cnum,$cdom)
                   15074: 
                   15075: Used in course context to determine if current file was uploaded to
                   15076: the course (i.e., would be found in /userfiles/docs on the course's
                   15077: homeserver.
                   15078: 
                   15079:   input: 3 args -- filename (decluttered), course number and course domain.
                   15080:   output: boolean -- 1 if file was uploaded.
                   15081: 
1.243     albertel 15082: =back
                   15083: 
                   15084: =head2 Storing/Retreiving Data
                   15085: 
                   15086: =over 4
1.191     harris41 15087: 
                   15088: =item *
                   15089: 
1.1172.2.64  raeburn  15090: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15091: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15092: the remaining args aren't required and if they aren't passed or are '' they will
                   15093: be derived from the env (with the exception of $laststore, which is an
                   15094: optional arg used when a user's submission is stored in grading).
                   15095: $laststore is $version=$timestamp, where $version is the most recent version
                   15096: number retrieved for the corresponding $symb in the $namespace db file, and
                   15097: $timestamp is the timestamp for that transaction (UNIX time).
                   15098: $laststore is currently only passed when cstore() is called by
                   15099: structuretags::finalize_storage().
1.191     harris41 15100: 
                   15101: =item *
                   15102: 
1.1172.2.64  raeburn  15103: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15104: but uses critical subroutine
1.191     harris41 15105: 
                   15106: =item *
                   15107: 
1.243     albertel 15108: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15109: all args are optional
1.191     harris41 15110: 
                   15111: =item *
                   15112: 
1.717     albertel 15113: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15114: dumps the complete (or key matching regexp) namespace into a hash
                   15115: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15116: normally &store()ed into
                   15117: 
                   15118: $range should be either an integer '100' (give me the first 100
                   15119:                                            matching records)
                   15120:               or be  two integers sperated by a - with no spaces
                   15121:                  '30-50' (give me the 30th through the 50th matching
                   15122:                           records)
                   15123: 
                   15124: 
                   15125: =item *
                   15126: 
1.1172.2.59  raeburn  15127: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15128: replaces a &store() version of data with a replacement set of data
                   15129: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15130: reference. If $tolog is true, the transaction is logged in the courselog
                   15131: with an action=PUTSTORE.
1.717     albertel 15132: 
                   15133: =item *
                   15134: 
1.243     albertel 15135: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15136: works very similar to store/cstore, but all data is stored in a
                   15137: temporary location and can be reset using tmpreset, $storehash should
                   15138: be a hash reference, returns nothing on success
1.191     harris41 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15143: similar to restore, but all data is stored in a temporary location and
                   15144: can be reset using tmpreset. Returns a hash of values on success,
                   15145: error string otherwise.
1.191     harris41 15146: 
                   15147: =item *
                   15148: 
1.243     albertel 15149: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15150: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15151: 
                   15152: =item *
                   15153: 
1.243     albertel 15154: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15155: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15156: 
                   15157: =item *
                   15158: 
1.243     albertel 15159: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15160: namesp ($udom and $uname are optional)
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.702     albertel 15164: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15165: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15166: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15167: 
1.702     albertel 15168: $range should be either an integer '100' (give me the first 100
                   15169:                                            matching records)
                   15170:               or be  two integers sperated by a - with no spaces
                   15171:                  '30-50' (give me the 30th through the 50th matching
                   15172:                           records)
1.449     matthew  15173: =item *
                   15174: 
                   15175: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15176: $store can be a scalar, an array reference, or if the amount to be 
                   15177: incremented is > 1, a hash reference.
                   15178: 
                   15179: ($udom and $uname are optional)
1.191     harris41 15180: 
                   15181: =item *
                   15182: 
1.243     albertel 15183: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15184: ($udom and $uname are optional)
1.191     harris41 15185: 
                   15186: =item *
                   15187: 
1.243     albertel 15188: cput($namespace,$storehash,$udom,$uname) : critical put
                   15189: ($udom and $uname are optional)
1.191     harris41 15190: 
                   15191: =item *
                   15192: 
1.748     albertel 15193: newput($namespace,$storehash,$udom,$uname) :
                   15194: 
                   15195: Attempts to store the items in the $storehash, but only if they don't
                   15196: currently exist, if this succeeds you can be certain that you have 
                   15197: successfully created a new key value pair in the $namespace db.
                   15198: 
                   15199: 
                   15200: Args:
                   15201:  $namespace: name of database to store values to
                   15202:  $storehash: hashref to store to the db
                   15203:  $udom: (optional) domain of user containing the db
                   15204:  $uname: (optional) name of user caontaining the db
                   15205: 
                   15206: Returns:
                   15207:  'ok' -> succeeded in storing all keys of $storehash
                   15208:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15209:                         least <key> already existed in the db (other
                   15210:                         requested keys may also already exist)
1.967     bisitz   15211:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15212:  'con_lost' -> unable to contact request server
                   15213:  'refused' -> action was not allowed by remote machine
                   15214: 
                   15215: 
                   15216: =item *
                   15217: 
1.243     albertel 15218: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15219: reference filled in from namesp (encrypts the return communication)
                   15220: ($udom and $uname are optional)
1.191     harris41 15221: 
                   15222: =item *
                   15223: 
1.243     albertel 15224: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15225: critical subroutine
                   15226: 
1.806     raeburn  15227: =item *
                   15228: 
1.860     raeburn  15229: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15230: array reference filled in from namespace found in domain level on either
                   15231: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15232: 
                   15233: =item *
                   15234: 
1.860     raeburn  15235: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15236: domain level either on specified domain server ($uhome) or primary domain 
                   15237: server ($udom and $uhome are optional)
1.806     raeburn  15238: 
1.943     raeburn  15239: =item * 
                   15240: 
1.1172.2.35  raeburn  15241: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15242: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15243: the target domain.
                   15244: 
                   15245: May also include additional key => value pairs for the following groups:
                   15246: 
                   15247: =over
                   15248: 
                   15249: =item
                   15250: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15251: 
                   15252: =over
                   15253: 
                   15254: =item defaultquota, authorquota
                   15255: 
                   15256: =back
                   15257: 
                   15258: =item
                   15259: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15260: portfolio for users).
                   15261: 
                   15262: =over
                   15263: 
                   15264: =item
                   15265: aboutme, blog, webdav, portfolio
                   15266: 
                   15267: =back
                   15268: 
                   15269: =item
                   15270: requestcourses: ability to request courses, and how requests are processed.
                   15271: 
                   15272: =over
                   15273: 
                   15274: =item
1.1172.2.37  raeburn  15275: official, unofficial, community, textbook
1.1172.2.35  raeburn  15276: 
                   15277: =back
                   15278: 
                   15279: =item
                   15280: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15281: 
                   15282: =over
                   15283: 
                   15284: =item
1.1172.2.44  raeburn  15285: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15286: 
                   15287: =back
                   15288: 
                   15289: =item
                   15290: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15291: for course's uploaded content.
                   15292: 
                   15293: =over
                   15294: 
                   15295: =item
1.1172.2.68  raeburn  15296: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15297: communityquota, textbookquota
1.1172.2.35  raeburn  15298: 
                   15299: =back
                   15300: 
                   15301: =item
                   15302: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15303: on your servers.
                   15304: 
                   15305: =over
                   15306: 
                   15307: =item
                   15308: remotesessions, hostedsessions
                   15309: 
                   15310: =back
                   15311: 
                   15312: =back
                   15313: 
                   15314: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15315: utility to create a configuration.db file on a domain's primary library server
                   15316: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15317: -- corresponding values are authentication type (internal, krb4, krb5,
                   15318: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15319: will be available. Values are retrieved from cache (if current), unless the
                   15320: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15321: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15322: 
                   15323: Typical usage:
1.943     raeburn  15324: 
1.1172.2.35  raeburn  15325: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15326: 
1.243     albertel 15327: =back
                   15328: 
                   15329: =head2 Network Status Functions
                   15330: 
                   15331: =over 4
1.191     harris41 15332: 
                   15333: =item *
                   15334: 
1.1137    raeburn  15335: dirlist() : return directory list based on URI (first arg).
                   15336: 
                   15337: Inputs: 1 required, 5 optional.
                   15338: 
                   15339: =over
                   15340: 
                   15341: =item 
                   15342: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15343: 
                   15344: =item
                   15345: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15346: 
                   15347: =item
                   15348: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15349: 
                   15350: =item
                   15351: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15352: 
                   15353: =item
                   15354: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15355: 
                   15356: =item 
                   15357: $alternateRoot - path to prepend in place of path from $uri.
                   15358: 
                   15359: =back
                   15360: 
                   15361: Returns: Array of up to two items.
                   15362: 
                   15363: =over
                   15364: 
                   15365: a reference to an array of files/subdirectories
                   15366: 
                   15367: =over
                   15368: 
                   15369: Each element in the array of files/subdirectories is a & separated list of
                   15370: item name and the result of running stat on the item.  If dirlist was requested
                   15371: for a file instead of a directory, the item name will be ''. For a directory 
                   15372: listing, if the item is a metadata file, the element will end &N&M 
                   15373: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15374: default copyright set (1).  
                   15375: 
                   15376: =back
                   15377: 
                   15378: a scalar containing error condition (if encountered).
                   15379: 
                   15380: =over
                   15381: 
                   15382: =item 
                   15383: no_host (no homeserver identified for $username:$domain).
                   15384: 
                   15385: =item 
                   15386: no_such_host (server contacted for listing not identified as valid host).
                   15387: 
                   15388: =item 
                   15389: con_lost (connection to remote server failed).
                   15390: 
                   15391: =item 
                   15392: refused (invalid $username:$domain received on lond side).
                   15393: 
                   15394: =item 
                   15395: no_such_dir (directory at specified path on lond side does not exist). 
                   15396: 
                   15397: =item 
                   15398: empty (directory at specified path on lond side is empty).
                   15399: 
                   15400: =over
                   15401: 
                   15402: This is currently not encountered because the &ls3, &ls2, 
                   15403: &ls (_handler) routines on the lond side do not filter out
                   15404: . and .. from a directory listing. 
                   15405: 
                   15406: =back
                   15407: 
                   15408: =back
                   15409: 
                   15410: =back
1.191     harris41 15411: 
                   15412: =item *
                   15413: 
1.243     albertel 15414: spareserver() : find server with least workload from spare.tab
                   15415: 
1.986     foxr     15416: 
                   15417: =item *
                   15418: 
                   15419: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15420: if there is no corresponding loncapa host.
                   15421: 
1.243     albertel 15422: =back
                   15423: 
1.986     foxr     15424: 
1.243     albertel 15425: =head2 Apache Request
                   15426: 
                   15427: =over 4
1.191     harris41 15428: 
                   15429: =item *
                   15430: 
1.243     albertel 15431: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15432: localhost, posts hash
                   15433: 
                   15434: =back
                   15435: 
                   15436: =head2 Data to String to Data
                   15437: 
                   15438: =over 4
1.191     harris41 15439: 
                   15440: =item *
                   15441: 
1.243     albertel 15442: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15443: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15444: 
                   15445: =item *
                   15446: 
1.243     albertel 15447: hashref2str($hashref) : convert a hashref into a string complete with
                   15448: escaping and '=' and '&' separators, supports elements that are
                   15449: arrayrefs and hashrefs
1.191     harris41 15450: 
                   15451: =item *
                   15452: 
1.243     albertel 15453: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15454: with escaping and '&' separators, supports elements that are arrayrefs
                   15455: and hashrefs
1.191     harris41 15456: 
                   15457: =item *
                   15458: 
1.243     albertel 15459: str2hash($string) : convert string to hash using unescaping and
                   15460: splitting on '=' and '&', supports elements that are arrayrefs and
                   15461: hashrefs
1.191     harris41 15462: 
                   15463: =item *
                   15464: 
1.243     albertel 15465: str2array($string) : convert string to hash using unescaping and
                   15466: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15467: 
                   15468: =back
                   15469: 
                   15470: =head2 Logging Routines
                   15471: 
                   15472: 
                   15473: These routines allow one to make log messages in the lonnet.log and
                   15474: lonnet.perm logfiles.
1.191     harris41 15475: 
1.1119    foxr     15476: =over 4
                   15477: 
1.191     harris41 15478: =item *
                   15479: 
1.243     albertel 15480: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15481: 
                   15482: =item *
                   15483: 
1.243     albertel 15484: logthis() : append message to the normal lonnet.log file, it gets
                   15485: preiodically rolled over and deleted.
1.191     harris41 15486: 
                   15487: =item *
                   15488: 
1.243     albertel 15489: logperm() : append a permanent message to lonnet.perm.log, this log
                   15490: file never gets deleted by any automated portion of the system, only
                   15491: messages of critical importance should go in here.
                   15492: 
1.1119    foxr     15493: 
1.243     albertel 15494: =back
                   15495: 
                   15496: =head2 General File Helper Routines
                   15497: 
                   15498: =over 4
1.191     harris41 15499: 
                   15500: =item *
                   15501: 
1.481     raeburn  15502: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15503: (a) files in /uploaded
                   15504:   (i) If a local copy of the file exists - 
                   15505:       compares modification date of local copy with last-modified date for 
                   15506:       definitive version stored on home server for course. If local copy is 
                   15507:       stale, requests a new version from the home server and stores it. 
                   15508:       If the original has been removed from the home server, then local copy 
                   15509:       is unlinked.
                   15510:   (ii) If local copy does not exist -
                   15511:       requests the file from the home server and stores it. 
                   15512:   
                   15513:   If $caller is 'uploadrep':  
                   15514:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15515:     for request for files originally uploaded via DOCS. 
                   15516:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15517:   
                   15518:   Otherwise:
                   15519:      This indicates a call from the content generation phase of the request.
                   15520:      -  returns the entire contents of the file or -1.
                   15521:      
                   15522: (b) files in /res
                   15523:    - returns the entire contents of a file or -1; 
                   15524:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15525: 
1.712     albertel 15526: 
                   15527: =item *
                   15528: 
                   15529: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15530:                   reference
                   15531: 
                   15532: returns either a stat() list of data about the file or an empty list
                   15533: if the file doesn't exist or couldn't find out about it (connection
                   15534: problems or user unknown)
                   15535: 
1.191     harris41 15536: =item *
                   15537: 
1.243     albertel 15538: filelocation($dir,$file) : returns file system location of a file
                   15539: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15540: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15541: and a file of ../bob will become /a/bob)
1.191     harris41 15542: 
                   15543: =item *
                   15544: 
                   15545: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15546: filelocation except for hrefs
                   15547: 
                   15548: =item *
                   15549: 
1.1172.2.49  raeburn  15550: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15551: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15552: 
1.243     albertel 15553: =back
                   15554: 
1.608     albertel 15555: =head2 Usererfile file routines (/uploaded*)
                   15556: 
                   15557: =over 4
                   15558: 
                   15559: =item *
                   15560: 
                   15561: userfileupload(): main rotine for putting a file in a user or course's
                   15562:                   filespace, arguments are,
                   15563: 
1.620     albertel 15564:  formname - required - this is the name of the element in $env where the
1.608     albertel 15565:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15566:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15567:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15568:  context - if coursedoc, store the file in the course of the active role
                   15569:              of the current user; 
                   15570:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15571:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15572:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15573:          if undefined, it will be placed in "unknown"
                   15574: 
                   15575:  (This routine calls clean_filename() to remove any dangerous
                   15576:  characters from the filename, and then calls finuserfileupload() to
                   15577:  complete the transaction)
                   15578: 
                   15579:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15580:  and /adm/notfound.html if unsuccessful
                   15581: 
                   15582: =item *
                   15583: 
                   15584: clean_filename(): routine for cleaing a filename up for storage in
                   15585:                  userfile space, argument is:
                   15586: 
                   15587:  filename - proposed filename
                   15588: 
                   15589: returns: the new clean filename
                   15590: 
                   15591: =item *
                   15592: 
1.1090    raeburn  15593: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15594: userspace, probably shouldn't be called directly
                   15595: 
                   15596:   docuname: username or courseid of destination for the file
                   15597:   docudom: domain of user/course of destination for the file
                   15598:   formname: same as for userfileupload()
1.1090    raeburn  15599:   fname: filename (including subdirectories) for the file
                   15600:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15601:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15602:   allfiles: reference to hash used to store objects found by parser
                   15603:   codebase: reference to hash used for codebases of java objects found by parser
                   15604:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15605:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15606:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15607:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15608:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15609:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15610:   mimetype: reference to scalar to accommodate mime type determined
                   15611:             from File::MMagic if $parser = parse.
1.608     albertel 15612: 
                   15613:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15614:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15615:  was 'overwrite').
                   15616:  
1.608     albertel 15617: 
                   15618: =item *
                   15619: 
                   15620: renameuserfile(): renames an existing userfile to a new name
                   15621: 
                   15622:   Args:
                   15623:    docuname: username or courseid of destination for the file
                   15624:    docudom: domain of user/course of destination for the file
                   15625:    old: current file name (including any subdirs under userfiles)
                   15626:    new: desired file name (including any subdirs under userfiles)
                   15627: 
                   15628: =item *
                   15629: 
                   15630: mkdiruserfile(): creates a directory is a userfiles dir
                   15631: 
                   15632:   Args:
                   15633:    docuname: username or courseid of destination for the file
                   15634:    docudom: domain of user/course of destination for the file
                   15635:    dir: dir to create (including any subdirs under userfiles)
                   15636: 
                   15637: =item *
                   15638: 
                   15639: removeuserfile(): removes a file that exists in userfiles
                   15640: 
                   15641:   Args:
                   15642:    docuname: username or courseid of destination for the file
                   15643:    docudom: domain of user/course of destination for the file
                   15644:    fname: filname to delete (including any subdirs under userfiles)
                   15645: 
                   15646: =item *
                   15647: 
                   15648: removeuploadedurl(): convience function for removeuserfile()
                   15649: 
                   15650:   Args:
                   15651:    url:  a full /uploaded/... url to delete
                   15652: 
1.747     albertel 15653: =item * 
                   15654: 
                   15655: get_portfile_permissions():
                   15656:   Args:
                   15657:     domain: domain of user or course contain the portfolio files
                   15658:     user: name of user or num of course contain the portfolio files
                   15659:   Returns:
                   15660:     hashref of a dump of the proper file_permissions.db
                   15661:    
                   15662: 
                   15663: =item * 
                   15664: 
                   15665: get_access_controls():
                   15666: 
                   15667: Args:
                   15668:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15669:   group: (optional) the group you want the files associated with
                   15670:   file: (optional) the file you want access info on
                   15671: 
                   15672: Returns:
1.749     raeburn  15673:     a hash (keys are file names) of hashes containing
                   15674:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15675:         values are XML containing access control settings (see below) 
1.747     albertel 15676: 
                   15677: Internal notes:
                   15678: 
1.749     raeburn  15679:  access controls are stored in file_permissions.db as key=value pairs.
                   15680:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15681:         where scope -> public,guest,course,group,domains or users.
                   15682:               end -> UNIX time for end of access (0 -> no end date)
                   15683:               start -> UNIX time for start of access
                   15684: 
                   15685:     value -> XML description of access control
                   15686:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15687:             <start></start>
                   15688:             <end></end>
                   15689: 
                   15690:             <password></password>  for scope type = guest
                   15691: 
                   15692:             <domain></domain>     for scope type = course or group
                   15693:             <number></number>
                   15694:             <roles id="">
                   15695:              <role></role>
                   15696:              <access></access>
                   15697:              <section></section>
                   15698:              <group></group>
                   15699:             </roles>
                   15700: 
                   15701:             <dom></dom>         for scope type = domains
                   15702: 
                   15703:             <users>             for scope type = users
                   15704:              <user>
                   15705:               <uname></uname>
                   15706:               <udom></udom>
                   15707:              </user>
                   15708:             </users>
                   15709:            </scope> 
                   15710:               
                   15711:  Access data is also aggregated for each file in an additional key=value pair:
                   15712:  key -> path to file/file_name\0accesscontrol 
                   15713:  value -> reference to hash
                   15714:           hash contains key = value pairs
                   15715:           where key = uniqueID:scope_end_start
                   15716:                 value = UNIX time record was last updated
                   15717: 
                   15718:           Used to improve speed of look-ups of access controls for each file.  
                   15719:  
                   15720:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15721: 
1.1172.2.13  raeburn  15722: =item *
                   15723: 
1.749     raeburn  15724: modify_access_controls():
                   15725: 
                   15726: Modifies access controls for a portfolio file
                   15727: Args
                   15728: 1. file name
                   15729: 2. reference to hash of required changes,
                   15730: 3. domain
                   15731: 4. username
                   15732:   where domain,username are the domain of the portfolio owner 
                   15733:   (either a user or a course) 
                   15734: 
                   15735: Returns:
                   15736: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15737: 2. result of deletions ('ok' or 'error', with error message).
                   15738: 3. reference to hash of any new or updated access controls.
                   15739: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15740:    key = integer (inbound ID)
1.1172.2.13  raeburn  15741:    value = uniqueID
                   15742: 
                   15743: =item *
                   15744: 
                   15745: get_timebased_id():
                   15746: 
                   15747: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15748: course via the Course Editor (e.g., folders, composite pages,
                   15749: group bulletin boards).
                   15750: 
                   15751: Args: (first three required; six others optional)
                   15752: 
                   15753: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15754:    docssequence, or name of group
                   15755: 
                   15756: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15757:    e.g., num, boardids
                   15758: 
                   15759: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15760:    file will be named nohist_namespace.db
                   15761: 
                   15762: 4. cdom: domain of course; default is current course domain from %env
                   15763: 
                   15764: 5. cnum: course number; default is current course number from %env
                   15765: 
                   15766: 6. idtype: set to concat if an additional digit is to be appended to the
                   15767:    unix timestamp to form the suffix, if the plain timestamp is already
                   15768:    in use.  Default is to not do this, but simply increment the unix
                   15769:    timestamp by 1 until a unique key is obtained.
                   15770: 
                   15771: 7. who: holder of locking key; defaults to user:domain for user.
                   15772: 
                   15773: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15774:    retrying); default is 3.
                   15775: 
                   15776: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15777: 
                   15778: Returns:
                   15779: 
                   15780: 1. suffix obtained (numeric)
                   15781: 
                   15782: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15783: 
                   15784: 3. error: contains (localized) error message if an error occurred.
                   15785: 
1.747     albertel 15786: 
1.608     albertel 15787: =back
                   15788: 
1.243     albertel 15789: =head2 HTTP Helper Routines
                   15790: 
                   15791: =over 4
                   15792: 
1.191     harris41 15793: =item *
                   15794: 
                   15795: escape() : unpack non-word characters into CGI-compatible hex codes
                   15796: 
                   15797: =item *
                   15798: 
                   15799: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15800: 
1.243     albertel 15801: =back
                   15802: 
                   15803: =head1 PRIVATE SUBROUTINES
                   15804: 
                   15805: =head2 Underlying communication routines (Shouldn't call)
                   15806: 
                   15807: =over 4
                   15808: 
                   15809: =item *
                   15810: 
                   15811: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15812: 
                   15813: =item *
                   15814: 
                   15815: reply() : uses subreply to send a message to remote machine, logs all failures
                   15816: 
                   15817: =item *
                   15818: 
                   15819: critical() : passes a critical message to another server; if cannot
                   15820: get through then place message in connection buffer directory and
                   15821: returns con_delayed, if incapable of saving message, returns
                   15822: con_failed
                   15823: 
                   15824: =item *
                   15825: 
                   15826: reconlonc() : tries to reconnect lonc client processes.
                   15827: 
                   15828: =back
                   15829: 
                   15830: =head2 Resource Access Logging
                   15831: 
                   15832: =over 4
                   15833: 
                   15834: =item *
                   15835: 
                   15836: flushcourselogs() : flush (save) buffer logs and access logs
                   15837: 
                   15838: =item *
                   15839: 
                   15840: courselog($what) : save message for course in hash
                   15841: 
                   15842: =item *
                   15843: 
                   15844: courseacclog($what) : save message for course using &courselog().  Perform
                   15845: special processing for specific resource types (problems, exams, quizzes, etc).
                   15846: 
1.191     harris41 15847: =item *
                   15848: 
                   15849: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15850: as a PerlChildExitHandler
1.243     albertel 15851: 
                   15852: =back
                   15853: 
                   15854: =head2 Other
                   15855: 
                   15856: =over 4
                   15857: 
                   15858: =item *
                   15859: 
                   15860: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15861: 
                   15862: =back
                   15863: 
                   15864: =cut
1.877     foxr     15865: 

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