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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.130! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.129 2020/10/15 19:20:25 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(?:[^.]+)$/) {
                   4690:                     $what.=':'.$formitem.'='.$env{$key};
                   4691:                 }
1.158     www      4692:             }
1.191     harris41 4693:         }
1.583     matthew  4694:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4695:         # FIXME: We should not be depending on a form parameter that someone
                   4696:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4697:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4698:             $what.= ':POST';
                   4699:             # FIXME: Probably ought to escape things....
                   4700:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4701:                                  'crsdiscuss') {
1.620     albertel 4702:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4703:             }
                   4704:         }
1.158     www      4705:     }
                   4706:     &courselog($what);
1.149     www      4707: }
                   4708: 
1.185     www      4709: sub countacc {
                   4710:     my $url=&declutter(shift);
1.458     matthew  4711:     return if (! defined($url) || $url eq '');
1.620     albertel 4712:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4713: #
                   4714: # Mark that this url was used in this course
                   4715: #
1.620     albertel 4716:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4717: #
                   4718: # Increase the access count for this resource in this child process
                   4719: #
1.281     www      4720:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4721:     $accesshash{$key}++;
1.185     www      4722: }
1.349     www      4723: 
1.361     www      4724: sub linklog {
                   4725:     my ($from,$to)=@_;
                   4726:     $from=&declutter($from);
                   4727:     $to=&declutter($to);
                   4728:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4729:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4730: }
1.1160    www      4731: 
                   4732: sub statslog {
                   4733:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4734:     if ($users<2) { return; }
                   4735:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4736:             'course'       => $env{'request.course.id'},
                   4737:             'sections'     => '"all"',
                   4738:             'num_students' => $users,
                   4739:             'part'         => $part,
                   4740:             'symb'         => $symb,
                   4741:             'mean_tries'   => $av_attempts,
                   4742:             'deg_of_diff'  => $degdiff});
                   4743:     foreach my $key (keys(%dynstore)) {
                   4744:         $accesshash{$key}=$dynstore{$key};
                   4745:     }
                   4746: }
1.361     www      4747:   
1.349     www      4748: sub userrolelog {
                   4749:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4750:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4751:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4752:        $userrolehash
                   4753:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4754:                     =$tend.':'.$tstart;
1.662     raeburn  4755:     }
1.1169    droeschl 4756:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4757:        $userrolehash
                   4758:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4759:                     =$tend.':'.$tstart;
                   4760:     }
1.1172.2.90  raeburn  4761:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4762:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4763:        $domainrolehash
                   4764:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4765:                     = $tend.':'.$tstart;
                   4766:     }
1.351     www      4767: }
                   4768: 
1.957     raeburn  4769: sub courserolelog {
                   4770:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4771:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4772:         my $cdom = $1;
                   4773:         my $cnum = $2;
                   4774:         my $sec = $3;
                   4775:         my $namespace = 'rolelog';
                   4776:         my %storehash = (
                   4777:                            role    => $trole,
                   4778:                            start   => $tstart,
                   4779:                            end     => $tend,
                   4780:                            selfenroll => $selfenroll,
                   4781:                            context    => $context,
                   4782:                         );
                   4783:         if ($trole eq 'gr') {
                   4784:             $namespace = 'groupslog';
                   4785:             $storehash{'group'} = $sec;
                   4786:         } else {
                   4787:             $storehash{'section'} = $sec;
                   4788:         }
                   4789:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4790:                    $domain,$cnum,$cdom);
                   4791:         if (($trole ne 'st') || ($sec ne '')) {
                   4792:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4793:         }
                   4794:     }
                   4795:     return;
                   4796: }
                   4797: 
1.1172.2.9  raeburn  4798: sub domainrolelog {
                   4799:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4800:     if ($area =~ m{^/($match_domain)/$}) {
                   4801:         my $cdom = $1;
                   4802:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4803:         my $namespace = 'rolelog';
                   4804:         my %storehash = (
                   4805:                            role    => $trole,
                   4806:                            start   => $tstart,
                   4807:                            end     => $tend,
                   4808:                            context => $context,
                   4809:                         );
                   4810:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4811:                    $domain,$domconfiguser,$cdom);
                   4812:     }
                   4813:     return;
                   4814: 
                   4815: }
                   4816: 
                   4817: sub coauthorrolelog {
                   4818:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4819:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4820:         my $audom = $1;
                   4821:         my $auname = $2;
                   4822:         my $namespace = 'rolelog';
                   4823:         my %storehash = (
                   4824:                            role    => $trole,
                   4825:                            start   => $tstart,
                   4826:                            end     => $tend,
                   4827:                            context => $context,
                   4828:                         );
                   4829:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4830:                    $domain,$auname,$audom);
                   4831:     }
                   4832:     return;
                   4833: }
                   4834: 
1.351     www      4835: sub get_course_adv_roles {
1.948     raeburn  4836:     my ($cid,$codes) = @_;
1.620     albertel 4837:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4838:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4839:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4840:     my %nothide=();
1.800     albertel 4841:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4842:         if ($user !~ /:/) {
                   4843: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4844:         } else {
                   4845:             $nothide{$user}=1;
                   4846:         }
1.470     www      4847:     }
1.1172.2.23  raeburn  4848:     my @possdoms = ($coursehash{'domain'});
                   4849:     if ($coursehash{'checkforpriv'}) {
                   4850:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4851:     }
1.351     www      4852:     my %returnhash=();
                   4853:     my %dumphash=
                   4854:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4855:     my $now=time;
1.997     raeburn  4856:     my %privileged;
1.1000    raeburn  4857:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4858: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4859:         if (($tstart) && ($tstart<0)) { next; }
                   4860:         if (($tend) && ($tend<$now)) { next; }
                   4861:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4862:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4863: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4864:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4865:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4866: 	if ($role eq 'cr') { next; }
1.948     raeburn  4867:         if ($codes) {
                   4868:             if ($section) { $role .= ':'.$section; }
                   4869:             if ($returnhash{$role}) {
                   4870:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4871:             } else {
                   4872:                 $returnhash{$role}=$username.':'.$domain;
                   4873:             }
1.351     www      4874:         } else {
1.988     raeburn  4875:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4876:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4877:             if ($returnhash{$key}) {
                   4878: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4879:             } else {
                   4880:                 $returnhash{$key}=$username.':'.$domain;
                   4881:             }
1.351     www      4882:         }
1.948     raeburn  4883:     }
1.400     www      4884:     return %returnhash;
                   4885: }
                   4886: 
                   4887: sub get_my_roles {
1.937     raeburn  4888:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4889:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4890:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4891:     my (%dumphash,%nothide);
1.1086    raeburn  4892:     if ($context eq 'userroles') {
1.1166    raeburn  4893:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4894:     } else {
1.1172.2.23  raeburn  4895:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4896:         if ($hidepriv) {
                   4897:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4898:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4899:                 if ($user !~ /:/) {
                   4900:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4901:                 } else {
                   4902:                     $nothide{$user} = 1;
                   4903:                 }
                   4904:             }
                   4905:         }
1.858     raeburn  4906:     }
1.400     www      4907:     my %returnhash=();
                   4908:     my $now=time;
1.999     raeburn  4909:     my %privileged;
1.800     albertel 4910:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4911:         my ($role,$tend,$tstart);
                   4912:         if ($context eq 'userroles') {
1.1149    raeburn  4913:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4914: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4915:         } else {
                   4916:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4917:         }
1.400     www      4918:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4919:         my $status = 'active';
1.939     raeburn  4920:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4921:             $status = 'previous';
                   4922:         } 
                   4923:         if (($tstart) && ($now<$tstart)) {
                   4924:             $status = 'future';
                   4925:         }
                   4926:         if (ref($types) eq 'ARRAY') {
                   4927:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4928:                 next;
                   4929:             } 
                   4930:         } else {
                   4931:             if ($status ne 'active') {
                   4932:                 next;
                   4933:             }
                   4934:         }
1.867     raeburn  4935:         my ($rolecode,$username,$domain,$section,$area);
                   4936:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4937:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4938:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4939:         } else {
                   4940:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4941:         }
1.832     raeburn  4942:         if (ref($roledoms) eq 'ARRAY') {
                   4943:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4944:                 next;
                   4945:             }
                   4946:         }
                   4947:         if (ref($roles) eq 'ARRAY') {
                   4948:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4949:                 if ($role =~ /^cr\//) {
                   4950:                     if (!grep(/^cr$/,@{$roles})) {
                   4951:                         next;
                   4952:                     }
1.1104    raeburn  4953:                 } elsif ($role =~ /^gr\//) {
                   4954:                     if (!grep(/^gr$/,@{$roles})) {
                   4955:                         next;
                   4956:                     }
1.922     raeburn  4957:                 } else {
                   4958:                     next;
                   4959:                 }
1.832     raeburn  4960:             }
1.867     raeburn  4961:         }
1.937     raeburn  4962:         if ($hidepriv) {
1.1172.2.23  raeburn  4963:             my @privroles = ('dc','su');
1.999     raeburn  4964:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4965:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4966:             } else {
1.1172.2.23  raeburn  4967:                 my $possdoms = [$domain];
                   4968:                 if (ref($roledoms) eq 'ARRAY') {
                   4969:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4970:                 }
1.1172.2.23  raeburn  4971:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4972:                     if (!$nothide{$username.':'.$domain}) {
                   4973:                         next;
                   4974:                     }
                   4975:                 }
1.937     raeburn  4976:             }
                   4977:         }
1.933     raeburn  4978:         if ($withsec) {
                   4979:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4980:                 $tstart.':'.$tend;
                   4981:         } else {
                   4982:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4983:         }
1.832     raeburn  4984:     }
1.373     www      4985:     return %returnhash;
1.399     www      4986: }
                   4987: 
1.1172.2.89  raeburn  4988: sub get_all_adhocroles {
                   4989:     my ($dom) = @_;
                   4990:     my @roles_by_num = ();
                   4991:     my %domdefaults = &get_domain_defaults($dom);
                   4992:     my (%description,%access_in_dom,%access_info);
                   4993:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4994:         my $count = 0;
                   4995:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4996:         my %ordered;
                   4997:         foreach my $role (sort(keys(%domcurrent))) {
                   4998:             my ($order,$desc,$access_in_dom);
                   4999:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5000:                 $order = $domcurrent{$role}{'order'};
                   5001:                 $desc = $domcurrent{$role}{'desc'};
                   5002:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5003:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5004:             }
                   5005:             if ($order eq '') {
                   5006:                 $order = $count;
                   5007:             }
                   5008:             $ordered{$order} = $role;
                   5009:             if ($desc ne '') {
                   5010:                 $description{$role} = $desc;
                   5011:             } else {
                   5012:                 $description{$role}= $role;
                   5013:             }
                   5014:             $count++;
                   5015:         }
                   5016:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5017:             push(@roles_by_num,$ordered{$item});
                   5018:         }
                   5019:     }
                   5020:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5021: }
                   5022: 
                   5023: sub get_my_adhocroles {
                   5024:     my ($cid,$checkreg) = @_;
                   5025:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5026:     if ($env{'request.course.id'} eq $cid) {
                   5027:         $cdom = $env{'course.'.$cid.'.domain'};
                   5028:         $cnum = $env{'course.'.$cid.'.num'};
                   5029:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5030:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5031:         $cdom = $1;
                   5032:         $cnum = $2;
                   5033:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5034:                                      $cdom,$cnum);
                   5035:     }
                   5036:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5037:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5038:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5039:         if ($rosterhash{$user} ne '') {
                   5040:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5041:             return ([],{}) if ($type eq 'auto');
                   5042:         }
                   5043:     }
                   5044:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5045:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5046:             my $then=$env{'user.login.time'};
                   5047:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5048:             if (!$update) {
                   5049:                 $update = $then;
                   5050:             }
                   5051:             my @liveroles;
                   5052:             foreach my $role ('dh','da') {
                   5053:                 if ($env{"user.role.$role./$cdom/"}) {
                   5054:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5055:                     my $limit = $update;
                   5056:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5057:                         $limit = $then;
                   5058:                     }
                   5059:                     my $activerole = 1;
                   5060:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5061:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5062:                     if ($activerole) {
                   5063:                         push(@liveroles,$role);
                   5064:                     }
                   5065:                 }
                   5066:             }
                   5067:             if (@liveroles) {
1.1172.2.89  raeburn  5068:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5069:                     my ($accessref,$accessinfo,%access_in_dom);
                   5070:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5071:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5072:                         if (@{$roles_by_num}) {
                   5073:                             my %settings;
                   5074:                             if ($env{'request.course.id'} eq $cid) {
                   5075:                                 foreach my $envkey (keys(%env)) {
                   5076:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5077:                                         $settings{$1} = $env{$envkey};
                   5078:                                     }
                   5079:                                 }
                   5080:                             } else {
                   5081:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5082:                             }
                   5083:                             my %setincrs;
                   5084:                             if ($settings{'internal.adhocaccess'}) {
                   5085:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5086:                             }
                   5087:                             my @statuses;
                   5088:                             if ($env{'environment.inststatus'}) {
                   5089:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5090:                             }
                   5091:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5092:                             if (ref($accessref) eq 'HASH') {
                   5093:                                 %access_in_dom = %{$accessref};
                   5094:                             }
                   5095:                             foreach my $role (@{$roles_by_num}) {
                   5096:                                 my ($curraccess,@okstatus,@personnel);
                   5097:                                 if ($setincrs{$role}) {
                   5098:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5099:                                     if ($curraccess eq 'status') {
                   5100:                                         @okstatus = split(/\&/,$rest);
                   5101:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5102:                                         @personnel = split(/\&/,$rest);
                   5103:                                     }
                   5104:                                 } else {
                   5105:                                     $curraccess = $access_in_dom{$role};
                   5106:                                     if (ref($accessinfo) eq 'HASH') {
                   5107:                                         if ($curraccess eq 'status') {
                   5108:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5109:                                                 @okstatus = @{$accessinfo->{$role}};
                   5110:                                             }
                   5111:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5112:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5113:                                                 @personnel = @{$accessinfo->{$role}};
                   5114:                                             }
                   5115:                                         }
                   5116:                                     }
                   5117:                                 }
                   5118:                                 if ($curraccess eq 'none') {
                   5119:                                     next;
                   5120:                                 } elsif ($curraccess eq 'all') {
                   5121:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5122:                                 } elsif ($curraccess eq 'dh') {
                   5123:                                     if (grep(/^dh$/,@liveroles)) {
                   5124:                                         push(@possroles,$role);
                   5125:                                     } else {
                   5126:                                         next;
                   5127:                                     }
                   5128:                                 } elsif ($curraccess eq 'da') {
                   5129:                                     if (grep(/^da$/,@liveroles)) {
                   5130:                                         push(@possroles,$role);
                   5131:                                     } else {
                   5132:                                         next;
                   5133:                                     }
1.1172.2.89  raeburn  5134:                                 } elsif ($curraccess eq 'status') {
                   5135:                                     if (@okstatus) {
                   5136:                                         if (!@statuses) {
                   5137:                                             if (grep(/^default$/,@okstatus)) {
                   5138:                                                 push(@possroles,$role);
                   5139:                                             }
                   5140:                                         } else {
                   5141:                                             foreach my $status (@okstatus) {
                   5142:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5143:                                                     push(@possroles,$role);
                   5144:                                                     last;
                   5145:                                                 }
                   5146:                                             }
                   5147:                                         }
                   5148:                                     }
                   5149:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5150:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5151:                                         if ($curraccess eq 'exc') {
                   5152:                                             push(@possroles,$role);
                   5153:                                         }
                   5154:                                     } elsif ($curraccess eq 'inc') {
                   5155:                                         push(@possroles,$role);
                   5156:                                     }
                   5157:                                 }
                   5158:                             }
                   5159:                         }
                   5160:                     }
                   5161:                 }
                   5162:             }
                   5163:         }
                   5164:     }
                   5165:     unless (ref($description) eq 'HASH') {
                   5166:         if (ref($roles_by_num) eq 'ARRAY') {
                   5167:             my %desc;
                   5168:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5169:             $description = \%desc;
                   5170:         } else {
                   5171:             $description = {};
                   5172:         }
                   5173:     }
                   5174:     return (\@possroles,$description);
                   5175: }
                   5176: 
1.399     www      5177: # ----------------------------------------------------- Frontpage Announcements
                   5178: #
                   5179: #
                   5180: 
                   5181: sub postannounce {
                   5182:     my ($server,$text)=@_;
1.844     albertel 5183:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5184:     unless ($text=~/\w/) { $text=''; }
                   5185:     return &reply('setannounce:'.&escape($text),$server);
                   5186: }
                   5187: 
                   5188: sub getannounce {
1.448     albertel 5189: 
1.1172.2.96  raeburn  5190:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5191: 	my $announcement='';
1.800     albertel 5192: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5193: 	close($fh);
1.399     www      5194: 	if ($announcement=~/\w/) { 
                   5195: 	    return 
                   5196:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5197:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5198: 	} else {
                   5199: 	    return '';
                   5200: 	}
                   5201:     } else {
                   5202: 	return '';
                   5203:     }
1.351     www      5204: }
1.353     www      5205: 
                   5206: # ---------------------------------------------------------- Course ID routines
                   5207: # Deal with domain's nohist_courseid.db files
                   5208: #
                   5209: 
                   5210: sub courseidput {
1.921     raeburn  5211:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5212:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5213:     my $outcome;
                   5214:     if ($caller eq 'timeonly') {
                   5215:         my $cids = '';
                   5216:         foreach my $item (keys(%$storehash)) {
                   5217:             $cids.=&escape($item).'&';
                   5218:         }
                   5219:         $cids=~s/\&$//;
                   5220:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5221:                           $coursehome);       
                   5222:     } else {
                   5223:         my $items = '';
                   5224:         foreach my $item (keys(%$storehash)) {
                   5225:             $items.= &escape($item).'='.
                   5226:                      &freeze_escape($$storehash{$item}).'&';
                   5227:         }
                   5228:         $items=~s/\&$//;
                   5229:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5230:                           $coursehome);
1.918     raeburn  5231:     }
                   5232:     if ($outcome eq 'unknown_cmd') {
                   5233:         my $what;
                   5234:         foreach my $cid (keys(%$storehash)) {
                   5235:             $what .= &escape($cid).'=';
1.921     raeburn  5236:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5237:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5238:             }
                   5239:             $what =~ s/\:$/&/;
                   5240:         }
                   5241:         $what =~ s/\&$//;  
                   5242:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5243:     } else {
                   5244:         return $outcome;
                   5245:     }
1.353     www      5246: }
                   5247: 
                   5248: sub courseiddump {
1.921     raeburn  5249:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5250:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5251:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5252:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5253:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5254:     my $as_hash = 1;
                   5255:     my %returnhash;
                   5256:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5257:     my %libserv = &all_library();
                   5258:     foreach my $tryserver (keys(%libserv)) {
                   5259:         if ( (  $hostidflag == 1 
                   5260: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5261: 	     || (!defined($hostidflag)) ) {
                   5262: 
1.918     raeburn  5263: 	    if (($domfilter eq '') ||
                   5264: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5265:                 my $rep;
                   5266:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5267:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5268:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5269:                                 &escape($descfilter), &escape($instcodefilter),
                   5270:                                 &escape($ownerfilter), &escape($coursefilter),
                   5271:                                 &escape($typefilter), &escape($regexp_ok),
                   5272:                                 $as_hash, &escape($selfenrollonly),
                   5273:                                 &escape($catfilter), $showhidden, $caller,
                   5274:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5275:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5276:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5277:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5278:                 } else {
                   5279:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5280:                              $sincefilter.':'.&escape($descfilter).':'.
                   5281:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5282:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5283:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5284:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5285:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5286:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5287:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5288:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5289:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5290:                 }
                   5291: 
1.918     raeburn  5292:                 my @pairs=split(/\&/,$rep);
                   5293:                 foreach my $item (@pairs) {
                   5294:                     my ($key,$value)=split(/\=/,$item,2);
                   5295:                     $key = &unescape($key);
                   5296:                     next if ($key =~ /^error: 2 /);
                   5297:                     my $result = &thaw_unescape($value);
                   5298:                     if (ref($result) eq 'HASH') {
                   5299:                         $returnhash{$key}=$result;
                   5300:                     } else {
1.921     raeburn  5301:                         my @responses = split(/:/,$value);
                   5302:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5303:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5304:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5305:                         }
1.1008    raeburn  5306:                     }
1.353     www      5307:                 }
                   5308:             }
                   5309:         }
                   5310:     }
                   5311:     return %returnhash;
                   5312: }
                   5313: 
1.1055    raeburn  5314: sub courselastaccess {
                   5315:     my ($cdom,$cnum,$hostidref) = @_;
                   5316:     my %returnhash;
                   5317:     if ($cdom && $cnum) {
                   5318:         my $chome = &homeserver($cnum,$cdom);
                   5319:         if ($chome ne 'no_host') {
                   5320:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5321:             &extract_lastaccess(\%returnhash,$rep);
                   5322:         }
                   5323:     } else {
                   5324:         if (!$cdom) { $cdom=''; }
                   5325:         my %libserv = &all_library();
                   5326:         foreach my $tryserver (keys(%libserv)) {
                   5327:             if (ref($hostidref) eq 'ARRAY') {
                   5328:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5329:             } 
                   5330:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5331:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5332:                 &extract_lastaccess(\%returnhash,$rep);
                   5333:             }
                   5334:         }
                   5335:     }
                   5336:     return %returnhash;
                   5337: }
                   5338: 
                   5339: sub extract_lastaccess {
                   5340:     my ($returnhash,$rep) = @_;
                   5341:     if (ref($returnhash) eq 'HASH') {
                   5342:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5343:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5344:                  $rep eq '') {
                   5345:             my @pairs=split(/\&/,$rep);
                   5346:             foreach my $item (@pairs) {
                   5347:                 my ($key,$value)=split(/\=/,$item,2);
                   5348:                 $key = &unescape($key);
                   5349:                 next if ($key =~ /^error: 2 /);
                   5350:                 $returnhash->{$key} = &thaw_unescape($value);
                   5351:             }
                   5352:         }
                   5353:     }
                   5354:     return;
                   5355: }
                   5356: 
1.658     raeburn  5357: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5358: 
                   5359: sub dcmailput {
1.685     raeburn  5360:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5361:     my $status = &Apache::lonnet::critical(
1.740     www      5362:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5363:        &escape($message),$server);
1.662     raeburn  5364:     return $status;
                   5365: }
                   5366: 
1.658     raeburn  5367: sub dcmaildump {
                   5368:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5369:     my %returnhash=();
1.846     albertel 5370: 
                   5371:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5372:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5373:                                                          &escape($enddate).':';
                   5374: 	my @esc_senders=map { &escape($_)} @$senders;
                   5375: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5376: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5377:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5378:             if (($key) && ($value)) {
                   5379:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5380:             }
                   5381:         }
                   5382:     }
                   5383:     return %returnhash;
                   5384: }
1.662     raeburn  5385: # ---------------------------------------------------------- Domain roles
                   5386: 
                   5387: sub get_domain_roles {
                   5388:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5389:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5390:         $startdate = '.';
                   5391:     }
1.1018    raeburn  5392:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5393:         $enddate = '.';
                   5394:     }
1.922     raeburn  5395:     my $rolelist;
                   5396:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5397:         $rolelist = join('&',@{$roles});
1.922     raeburn  5398:     }
1.662     raeburn  5399:     my %personnel = ();
1.841     albertel 5400: 
                   5401:     my %servers = &get_servers($dom,'library');
                   5402:     foreach my $tryserver (keys(%servers)) {
                   5403: 	%{$personnel{$tryserver}}=();
                   5404: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5405: 					    &escape($startdate).':'.
                   5406: 					    &escape($enddate).':'.
                   5407: 					    &escape($rolelist), $tryserver))) {
                   5408: 	    my ($key,$value) = split(/\=/,$line,2);
                   5409: 	    if (($key) && ($value)) {
                   5410: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5411: 	    }
                   5412: 	}
1.662     raeburn  5413:     }
                   5414:     return %personnel;
                   5415: }
1.658     raeburn  5416: 
1.1172.2.89  raeburn  5417: sub get_active_domroles {
                   5418:     my ($dom,$roles) = @_;
                   5419:     return () unless (ref($roles) eq 'ARRAY');
                   5420:     my $now = time;
                   5421:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5422:     my %domroles;
                   5423:     foreach my $server (keys(%dompersonnel)) {
                   5424:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5425:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5426:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5427:         }
                   5428:     }
                   5429:     return %domroles;
                   5430: }
                   5431: 
1.1057    www      5432: # ----------------------------------------------------------- Interval timing 
1.149     www      5433: 
1.1153    www      5434: {
                   5435: # Caches needed for speedup of navmaps
                   5436: # We don't want to cache this for very long at all (5 seconds at most)
                   5437: # 
                   5438: # The user for whom we cache
                   5439: my $cachedkey='';
                   5440: # The cached times for this user
                   5441: my %cachedtimes=();
                   5442: # When this was last done
1.1172.2.66  raeburn  5443: my $cachedtime='';
1.1153    www      5444: 
                   5445: sub load_all_first_access {
1.1154    raeburn  5446:     my ($uname,$udom)=@_;
1.1156    www      5447:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5448:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5449:         return;
                   5450:     }
                   5451:     $cachedtime=time;
                   5452:     $cachedkey=$uname.':'.$udom;
                   5453:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5454: }
                   5455: 
1.504     albertel 5456: sub get_first_access {
1.1162    raeburn  5457:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5458:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5459:     if ($argsymb) { $symb=$argsymb; }
                   5460:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5461:     if ($argmap) { $map = $argmap; }
1.926     albertel 5462:     if ($type eq 'course') {
                   5463: 	$res='course';
                   5464:     } elsif ($type eq 'map') {
1.588     albertel 5465: 	$res=&symbread($map);
                   5466:     } else {
                   5467: 	$res=$symb;
                   5468:     }
1.1153    www      5469:     &load_all_first_access($uname,$udom);
                   5470:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5471: }
                   5472: 
                   5473: sub set_first_access {
1.1162    raeburn  5474:     my ($type,$interval)=@_;
1.790     albertel 5475:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5476:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5477:     if ($type eq 'course') {
                   5478: 	$res='course';
                   5479:     } elsif ($type eq 'map') {
1.588     albertel 5480: 	$res=&symbread($map);
                   5481:     } else {
                   5482: 	$res=$symb;
                   5483:     }
1.1153    www      5484:     $cachedkey='';
1.1162    raeburn  5485:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5486:     if ($firstaccess) {
                   5487:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5488:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5489:                  "in $courseid");
                   5490:         return 'already_set';
                   5491:     } else {
1.1162    raeburn  5492:         my $start = time;
                   5493: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5494:                           $udom,$uname);
                   5495:         if ($putres eq 'ok') {
                   5496:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5497:                  $udom,$uname); 
                   5498:             &appenv(
                   5499:                      {
                   5500:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5501:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5502:                      }
                   5503:                   );
1.1172.2.97  raeburn  5504:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5505:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5506:             }
1.1172.2.102  raeburn  5507:         } elsif ($putres ne 'refused') {
                   5508:             &logthis("Result: $putres when attempting to set first access time ".
                   5509:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5510:         }
                   5511:         return $putres;
1.505     albertel 5512:     }
                   5513:     return 'already_set';
1.504     albertel 5514: }
1.1153    www      5515: }
1.1172.2.32  raeburn  5516: 
                   5517: sub checkout {
                   5518:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5519:     my $now=time;
                   5520:     my $lonhost=$perlvar{'lonHostID'};
                   5521:     my $infostr=&escape(
                   5522:                  'CHECKOUTTOKEN&'.
                   5523:                  $tuname.'&'.
                   5524:                  $tudom.'&'.
                   5525:                  $tcrsid.'&'.
                   5526:                  $symb.'&'.
                   5527:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5528:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5529:     if ($token=~/^error\:/) {
                   5530:         &logthis("<font color=\"blue\">WARNING: ".
                   5531:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5532:                  "</font>");
                   5533:         return '';
                   5534:     }
                   5535: 
                   5536:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5537:     $token=~tr/a-z/A-Z/;
                   5538: 
                   5539:     my %infohash=('resource.0.outtoken' => $token,
                   5540:                   'resource.0.checkouttime' => $now,
                   5541:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5542: 
                   5543:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5544:        return '';
                   5545:     } else {
                   5546:         &logthis("<font color=\"blue\">WARNING: ".
                   5547:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5548:                  "</font>");
                   5549:     }
                   5550: 
                   5551:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5552:                          &escape('Checkout '.$infostr.' - '.
                   5553:                                                  $token)) ne 'ok') {
                   5554:         return '';
                   5555:     } else {
                   5556:         &logthis("<font color=\"blue\">WARNING: ".
                   5557:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5558:                  "</font>");
                   5559:     }
                   5560:     return $token;
                   5561: }
                   5562: 
                   5563: # ------------------------------------------------------------ Check in an item
                   5564: 
                   5565: sub checkin {
                   5566:     my $token=shift;
                   5567:     my $now=time;
                   5568:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5569:     $lonhost=~tr/A-Z/a-z/;
                   5570:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5571:     $dtoken=~s/\W/\_/g;
                   5572:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5573:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5574: 
                   5575:     unless (($tuname) && ($tudom)) {
                   5576:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5577:         return '';
                   5578:     }
                   5579: 
                   5580:     unless (&allowed('mgr',$tcrsid)) {
                   5581:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5582:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5583:         return '';
                   5584:     }
                   5585: 
                   5586:     my %infohash=('resource.0.intoken' => $token,
                   5587:                   'resource.0.checkintime' => $now,
                   5588:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5589: 
                   5590:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5591:        return '';
                   5592:     }
                   5593: 
                   5594:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5595:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5596:         return '';
                   5597:     }
                   5598: 
                   5599:     return ($symb,$tuname,$tudom,$tcrsid);
                   5600: }
                   5601: 
1.110     www      5602: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5603: 
                   5604: sub expirespread {
                   5605:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5606:     my $cid=$env{'request.course.id'}; 
1.110     www      5607:     if ($cid) {
                   5608:        my $now=time;
                   5609:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5610:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5611:                             $env{'course.'.$cid.'.num'}.
1.110     www      5612: 	        	    ':nohist_expirationdates:'.
                   5613:                             &escape($key).'='.$now,
1.620     albertel 5614:                             $env{'course.'.$cid.'.home'})
1.110     www      5615:     }
                   5616:     return 'ok';
1.14      www      5617: }
                   5618: 
1.109     www      5619: # ----------------------------------------------------- Devalidate Spreadsheets
                   5620: 
                   5621: sub devalidate {
1.325     www      5622:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5623:     my $cid=$env{'request.course.id'}; 
1.109     www      5624:     if ($cid) {
1.391     matthew  5625:         # delete the stored spreadsheets for
                   5626:         # - the student level sheet of this user in course's homespace
                   5627:         # - the assessment level sheet for this resource 
                   5628:         #   for this user in user's homespace
1.553     albertel 5629: 	# - current conditional state info
1.325     www      5630: 	my $key=$uname.':'.$udom.':';
1.109     www      5631:         my $status=
1.299     matthew  5632: 	    &del('nohist_calculatedsheets',
1.391     matthew  5633: 		 [$key.'studentcalc:'],
1.620     albertel 5634: 		 $env{'course.'.$cid.'.domain'},
                   5635: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5636: 		.' '.
                   5637: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5638: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5639:         unless ($status eq 'ok ok') {
                   5640:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5641:                     $uname.' at '.$udom.' for '.
1.109     www      5642: 		    $symb.': '.$status);
1.133     albertel 5643:         }
1.553     albertel 5644: 	&delenv('user.state.'.$cid);
1.109     www      5645:     }
                   5646: }
                   5647: 
1.265     albertel 5648: sub get_scalar {
                   5649:     my ($string,$end) = @_;
                   5650:     my $value;
                   5651:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5652: 	$value = $1;
                   5653:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5654: 	$value = $1;
                   5655:     }
                   5656:     return &unescape($value);
                   5657: }
                   5658: 
                   5659: sub array2str {
                   5660:   my (@array) = @_;
                   5661:   my $result=&arrayref2str(\@array);
                   5662:   $result=~s/^__ARRAY_REF__//;
                   5663:   $result=~s/__END_ARRAY_REF__$//;
                   5664:   return $result;
                   5665: }
                   5666: 
1.204     albertel 5667: sub arrayref2str {
                   5668:   my ($arrayref) = @_;
1.265     albertel 5669:   my $result='__ARRAY_REF__';
1.204     albertel 5670:   foreach my $elem (@$arrayref) {
1.265     albertel 5671:     if(ref($elem) eq 'ARRAY') {
                   5672:       $result.=&arrayref2str($elem).'&';
                   5673:     } elsif(ref($elem) eq 'HASH') {
                   5674:       $result.=&hashref2str($elem).'&';
                   5675:     } elsif(ref($elem)) {
                   5676:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5677:     } else {
                   5678:       $result.=&escape($elem).'&';
                   5679:     }
                   5680:   }
                   5681:   $result=~s/\&$//;
1.265     albertel 5682:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5683:   return $result;
                   5684: }
                   5685: 
1.168     albertel 5686: sub hash2str {
1.204     albertel 5687:   my (%hash) = @_;
                   5688:   my $result=&hashref2str(\%hash);
1.265     albertel 5689:   $result=~s/^__HASH_REF__//;
                   5690:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5691:   return $result;
                   5692: }
                   5693: 
                   5694: sub hashref2str {
                   5695:   my ($hashref)=@_;
1.265     albertel 5696:   my $result='__HASH_REF__';
1.800     albertel 5697:   foreach my $key (sort(keys(%$hashref))) {
                   5698:     if (ref($key) eq 'ARRAY') {
                   5699:       $result.=&arrayref2str($key).'=';
                   5700:     } elsif (ref($key) eq 'HASH') {
                   5701:       $result.=&hashref2str($key).'=';
                   5702:     } elsif (ref($key)) {
1.265     albertel 5703:       $result.='=';
1.800     albertel 5704:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5705:     } else {
1.1132    raeburn  5706: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5707:     }
                   5708: 
1.800     albertel 5709:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5710:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5711:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5712:       $result.=&hashref2str($hashref->{$key}).'&';
                   5713:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5714:        $result.='&';
1.800     albertel 5715:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5716:     } else {
1.800     albertel 5717:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5718:     }
                   5719:   }
1.168     albertel 5720:   $result=~s/\&$//;
1.265     albertel 5721:   $result .= '__END_HASH_REF__';
1.168     albertel 5722:   return $result;
                   5723: }
                   5724: 
                   5725: sub str2hash {
1.265     albertel 5726:     my ($string)=@_;
                   5727:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5728:     return %$hash;
                   5729: }
                   5730: 
                   5731: sub str2hashref {
1.168     albertel 5732:   my ($string) = @_;
1.265     albertel 5733: 
                   5734:   my %hash;
                   5735: 
                   5736:   if($string !~ /^__HASH_REF__/) {
                   5737:       if (! ($string eq '' || !defined($string))) {
                   5738: 	  $hash{'error'}='Not hash reference';
                   5739:       }
                   5740:       return (\%hash, $string);
                   5741:   }
                   5742: 
                   5743:   $string =~ s/^__HASH_REF__//;
                   5744: 
                   5745:   while($string !~ /^__END_HASH_REF__/) {
                   5746:       #key
                   5747:       my $key='';
                   5748:       if($string =~ /^__HASH_REF__/) {
                   5749:           ($key, $string)=&str2hashref($string);
                   5750:           if(defined($key->{'error'})) {
                   5751:               $hash{'error'}='Bad data';
                   5752:               return (\%hash, $string);
                   5753:           }
                   5754:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5755:           ($key, $string)=&str2arrayref($string);
                   5756:           if($key->[0] eq 'Array reference error') {
                   5757:               $hash{'error'}='Bad data';
                   5758:               return (\%hash, $string);
                   5759:           }
                   5760:       } else {
                   5761:           $string =~ s/^(.*?)=//;
1.267     albertel 5762: 	  $key=&unescape($1);
1.265     albertel 5763:       }
                   5764:       $string =~ s/^=//;
                   5765: 
                   5766:       #value
                   5767:       my $value='';
                   5768:       if($string =~ /^__HASH_REF__/) {
                   5769:           ($value, $string)=&str2hashref($string);
                   5770:           if(defined($value->{'error'})) {
                   5771:               $hash{'error'}='Bad data';
                   5772:               return (\%hash, $string);
                   5773:           }
                   5774:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5775:           ($value, $string)=&str2arrayref($string);
                   5776:           if($value->[0] eq 'Array reference error') {
                   5777:               $hash{'error'}='Bad data';
                   5778:               return (\%hash, $string);
                   5779:           }
                   5780:       } else {
                   5781: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5782:       }
                   5783:       $string =~ s/^&//;
                   5784: 
                   5785:       $hash{$key}=$value;
1.204     albertel 5786:   }
1.265     albertel 5787: 
                   5788:   $string =~ s/^__END_HASH_REF__//;
                   5789: 
                   5790:   return (\%hash, $string);
1.204     albertel 5791: }
                   5792: 
                   5793: sub str2array {
1.265     albertel 5794:     my ($string)=@_;
                   5795:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5796:     return @$array;
                   5797: }
                   5798: 
                   5799: sub str2arrayref {
1.204     albertel 5800:   my ($string) = @_;
1.265     albertel 5801:   my @array;
                   5802: 
                   5803:   if($string !~ /^__ARRAY_REF__/) {
                   5804:       if (! ($string eq '' || !defined($string))) {
                   5805: 	  $array[0]='Array reference error';
                   5806:       }
                   5807:       return (\@array, $string);
                   5808:   }
                   5809: 
                   5810:   $string =~ s/^__ARRAY_REF__//;
                   5811: 
                   5812:   while($string !~ /^__END_ARRAY_REF__/) {
                   5813:       my $value='';
                   5814:       if($string =~ /^__HASH_REF__/) {
                   5815:           ($value, $string)=&str2hashref($string);
                   5816:           if(defined($value->{'error'})) {
                   5817:               $array[0] ='Array reference error';
                   5818:               return (\@array, $string);
                   5819:           }
                   5820:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5821:           ($value, $string)=&str2arrayref($string);
                   5822:           if($value->[0] eq 'Array reference error') {
                   5823:               $array[0] ='Array reference error';
                   5824:               return (\@array, $string);
                   5825:           }
                   5826:       } else {
                   5827: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5828:       }
                   5829:       $string =~ s/^&//;
                   5830: 
                   5831:       push(@array, $value);
1.191     harris41 5832:   }
1.265     albertel 5833: 
                   5834:   $string =~ s/^__END_ARRAY_REF__//;
                   5835: 
                   5836:   return (\@array, $string);
1.168     albertel 5837: }
                   5838: 
1.167     albertel 5839: # -------------------------------------------------------------------Temp Store
                   5840: 
1.168     albertel 5841: sub tmpreset {
                   5842:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5843:   if (!$symb) {
                   5844:     $symb=&symbread();
1.620     albertel 5845:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5846:   }
                   5847:   $symb=escape($symb);
                   5848: 
1.620     albertel 5849:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5850:   $namespace=~s/\//\_/g;
                   5851:   $namespace=~s/\W//g;
                   5852: 
1.620     albertel 5853:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5854:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5855:   if ($domain eq 'public' && $stuname eq 'public') {
                   5856:       $stuname=$ENV{'REMOTE_ADDR'};
                   5857:   }
1.1117    foxr     5858:   my $path=LONCAPA::tempdir();
1.168     albertel 5859:   my %hash;
                   5860:   if (tie(%hash,'GDBM_File',
                   5861: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5862: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5863:     foreach my $key (keys(%hash)) {
1.180     albertel 5864:       if ($key=~ /:$symb/) {
1.168     albertel 5865: 	delete($hash{$key});
                   5866:       }
                   5867:     }
                   5868:   }
                   5869: }
                   5870: 
1.167     albertel 5871: sub tmpstore {
1.168     albertel 5872:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5873: 
                   5874:   if (!$symb) {
                   5875:     $symb=&symbread();
1.620     albertel 5876:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5877:   }
                   5878:   $symb=escape($symb);
                   5879: 
                   5880:   if (!$namespace) {
                   5881:     # I don't think we would ever want to store this for a course.
                   5882:     # it seems this will only be used if we don't have a course.
1.620     albertel 5883:     #$namespace=$env{'request.course.id'};
1.168     albertel 5884:     #if (!$namespace) {
1.620     albertel 5885:       $namespace=$env{'request.state'};
1.168     albertel 5886:     #}
                   5887:   }
                   5888:   $namespace=~s/\//\_/g;
                   5889:   $namespace=~s/\W//g;
1.620     albertel 5890:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5891:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5892:   if ($domain eq 'public' && $stuname eq 'public') {
                   5893:       $stuname=$ENV{'REMOTE_ADDR'};
                   5894:   }
1.168     albertel 5895:   my $now=time;
                   5896:   my %hash;
1.1117    foxr     5897:   my $path=LONCAPA::tempdir();
1.168     albertel 5898:   if (tie(%hash,'GDBM_File',
                   5899: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5900: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5901:     $hash{"version:$symb"}++;
                   5902:     my $version=$hash{"version:$symb"};
                   5903:     my $allkeys=''; 
                   5904:     foreach my $key (keys(%$storehash)) {
                   5905:       $allkeys.=$key.':';
1.591     albertel 5906:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5907:     }
                   5908:     $hash{"$version:$symb:timestamp"}=$now;
                   5909:     $allkeys.='timestamp';
                   5910:     $hash{"$version:keys:$symb"}=$allkeys;
                   5911:     if (untie(%hash)) {
                   5912:       return 'ok';
                   5913:     } else {
                   5914:       return "error:$!";
                   5915:     }
                   5916:   } else {
                   5917:     return "error:$!";
                   5918:   }
                   5919: }
1.167     albertel 5920: 
1.168     albertel 5921: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5922: 
1.168     albertel 5923: sub tmprestore {
                   5924:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5925: 
1.168     albertel 5926:   if (!$symb) {
                   5927:     $symb=&symbread();
1.620     albertel 5928:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5929:   }
                   5930:   $symb=escape($symb);
                   5931: 
1.620     albertel 5932:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5933: 
1.620     albertel 5934:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5935:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5936:   if ($domain eq 'public' && $stuname eq 'public') {
                   5937:       $stuname=$ENV{'REMOTE_ADDR'};
                   5938:   }
1.168     albertel 5939:   my %returnhash;
                   5940:   $namespace=~s/\//\_/g;
                   5941:   $namespace=~s/\W//g;
                   5942:   my %hash;
1.1117    foxr     5943:   my $path=LONCAPA::tempdir();
1.168     albertel 5944:   if (tie(%hash,'GDBM_File',
                   5945: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5946: 	  &GDBM_READER(),0640)) {
1.168     albertel 5947:     my $version=$hash{"version:$symb"};
                   5948:     $returnhash{'version'}=$version;
                   5949:     my $scope;
                   5950:     for ($scope=1;$scope<=$version;$scope++) {
                   5951:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5952:       my @keys=split(/:/,$vkeys);
                   5953:       my $key;
                   5954:       $returnhash{"$scope:keys"}=$vkeys;
                   5955:       foreach $key (@keys) {
1.591     albertel 5956: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5957: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5958:       }
                   5959:     }
1.168     albertel 5960:     if (!(untie(%hash))) {
                   5961:       return "error:$!";
                   5962:     }
                   5963:   } else {
                   5964:     return "error:$!";
                   5965:   }
                   5966:   return %returnhash;
1.167     albertel 5967: }
                   5968: 
1.9       www      5969: # ----------------------------------------------------------------------- Store
                   5970: 
                   5971: sub store {
1.1172.2.64  raeburn  5972:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5973:     my $home='';
                   5974: 
1.168     albertel 5975:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5976: 
1.213     www      5977:     $symb=&symbclean($symb);
1.122     albertel 5978:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5979: 
1.620     albertel 5980:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5981:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5982: 
                   5983:     &devalidate($symb,$stuname,$domain);
1.109     www      5984: 
                   5985:     $symb=escape($symb);
1.187     www      5986:     if (!$namespace) { 
1.620     albertel 5987:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5988:           return ''; 
                   5989:        } 
                   5990:     }
1.620     albertel 5991:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5992: 
                   5993:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5994:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5995: 
1.12      www      5996:     my $namevalue='';
1.800     albertel 5997:     foreach my $key (keys(%$storehash)) {
                   5998:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5999:     }
1.12      www      6000:     $namevalue=~s/\&$//;
1.187     www      6001:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6002:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6003: }
                   6004: 
1.47      www      6005: # -------------------------------------------------------------- Critical Store
                   6006: 
                   6007: sub cstore {
1.1172.2.64  raeburn  6008:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6009:     my $home='';
                   6010: 
1.168     albertel 6011:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6012: 
1.213     www      6013:     $symb=&symbclean($symb);
1.122     albertel 6014:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6015: 
1.620     albertel 6016:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6017:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6018: 
                   6019:     &devalidate($symb,$stuname,$domain);
1.109     www      6020: 
                   6021:     $symb=escape($symb);
1.187     www      6022:     if (!$namespace) { 
1.620     albertel 6023:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6024:           return ''; 
                   6025:        } 
                   6026:     }
1.620     albertel 6027:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6028: 
                   6029:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6030:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6031: 
1.47      www      6032:     my $namevalue='';
1.800     albertel 6033:     foreach my $key (keys(%$storehash)) {
                   6034:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6035:     }
1.47      www      6036:     $namevalue=~s/\&$//;
1.187     www      6037:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6038:     return critical
1.1172.2.64  raeburn  6039:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6040: }
                   6041: 
1.9       www      6042: # --------------------------------------------------------------------- Restore
                   6043: 
                   6044: sub restore {
1.124     www      6045:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6046:     my $home='';
                   6047: 
1.168     albertel 6048:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6049: 
1.122     albertel 6050:     if (!$symb) {
1.1172.2.26  raeburn  6051:         return if ($namespace eq 'courserequests');
                   6052:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6053:     } else {
1.1172.2.26  raeburn  6054:         unless ($namespace eq 'courserequests') {
                   6055:             $symb=&escape(&symbclean($symb));
                   6056:         }
1.122     albertel 6057:     }
1.188     www      6058:     if (!$namespace) { 
1.620     albertel 6059:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6060:           return ''; 
                   6061:        } 
                   6062:     }
1.620     albertel 6063:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6064:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6065:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6066:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6067: 
1.12      www      6068:     my %returnhash=();
1.800     albertel 6069:     foreach my $line (split(/\&/,$answer)) {
                   6070: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6071:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6072:     }
1.75      www      6073:     my $version;
                   6074:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6075:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6076:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6077:        }
1.75      www      6078:     }
1.13      www      6079:     return %returnhash;
1.34      www      6080: }
                   6081: 
                   6082: # ---------------------------------------------------------- Course Description
1.1118    foxr     6083: #
                   6084: #  
1.34      www      6085: 
                   6086: sub coursedescription {
1.731     albertel 6087:     my ($courseid,$args)=@_;
1.34      www      6088:     $courseid=~s/^\///;
1.49      www      6089:     $courseid=~s/\_/\//g;
1.34      www      6090:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6091:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6092:     my $normalid=$cdomain.'_'.$cnum;
                   6093:     # need to always cache even if we get errors otherwise we keep 
                   6094:     # trying and trying and trying to get the course description.
                   6095:     my %envhash=();
                   6096:     my %returnhash=();
1.731     albertel 6097:     
                   6098:     my $expiretime=600;
                   6099:     if ($env{'request.course.id'} eq $normalid) {
                   6100: 	$expiretime=120;
                   6101:     }
                   6102: 
                   6103:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6104:     if (!$args->{'freshen_cache'}
                   6105: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6106: 	foreach my $key (keys(%env)) {
                   6107: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6108: 	    my ($setting) = $1;
                   6109: 	    $returnhash{$setting} = $env{$key};
                   6110: 	}
                   6111: 	return %returnhash;
                   6112:     }
                   6113: 
1.1118    foxr     6114:     # get the data again
                   6115: 
1.731     albertel 6116:     if (!$args->{'one_time'}) {
                   6117: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6118:     }
1.811     albertel 6119: 
1.34      www      6120:     if ($chome ne 'no_host') {
1.302     albertel 6121:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6122:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6123: 	   my $username = $env{'user.name'}; # Defult username
                   6124: 	   if(defined $args->{'user'}) {
                   6125: 	       $username = $args->{'user'};
                   6126: 	   }
1.129     albertel 6127:            $returnhash{'home'}= $chome;
                   6128: 	   $returnhash{'domain'} = $cdomain;
                   6129: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6130:            if (!defined($returnhash{'type'})) {
                   6131:                $returnhash{'type'} = 'Course';
                   6132:            }
1.130     albertel 6133:            while (my ($name,$value) = each %returnhash) {
1.53      www      6134:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6135:            }
1.270     www      6136:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6137:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6138: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6139:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6140:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6141:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6142:        }
                   6143:     }
1.731     albertel 6144:     if (!$args->{'one_time'}) {
1.949     raeburn  6145: 	&appenv(\%envhash);
1.731     albertel 6146:     }
1.302     albertel 6147:     return %returnhash;
1.461     www      6148: }
                   6149: 
1.1080    raeburn  6150: sub update_released_required {
                   6151:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6152:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6153:         $cid = $env{'request.course.id'};
                   6154:         $cdom = $env{'course.'.$cid.'.domain'};
                   6155:         $cnum = $env{'course.'.$cid.'.num'};
                   6156:         $chome = $env{'course.'.$cid.'.home'};
                   6157:     }
                   6158:     if ($needsrelease) {
                   6159:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6160:         my $needsupdate;
                   6161:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6162:             $needsupdate = 1;
                   6163:         } else {
                   6164:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6165:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6166:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6167:                 $needsupdate = 1;
                   6168:             }
                   6169:         }
                   6170:         if ($needsupdate) {
                   6171:             my %needshash = (
                   6172:                              'internal.releaserequired' => $needsrelease,
                   6173:                             );
                   6174:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6175:             if ($putresult eq 'ok') {
                   6176:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6177:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6178:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6179:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6180:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6181:                 }
                   6182:             }
                   6183:         }
                   6184:     }
                   6185:     return;
                   6186: }
                   6187: 
1.461     www      6188: # -------------------------------------------------See if a user is privileged
                   6189: 
                   6190: sub privileged {
1.1172.2.23  raeburn  6191:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6192:     my $now = time;
1.1172.2.23  raeburn  6193:     my $roles;
                   6194:     if (ref($possroles) eq 'ARRAY') {
                   6195:         $roles = $possroles;
                   6196:     } else {
                   6197:         $roles = ['dc','su'];
                   6198:     }
                   6199:     if (ref($possdomains) eq 'ARRAY') {
                   6200:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6201:         foreach my $dom (@{$possdomains}) {
                   6202:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6203:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6204:                 foreach my $role (@{$roles}) {
                   6205:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6206:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6207:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6208:                             return 1 unless (($end && $end < $now) ||
                   6209:                                              ($start && $start > $now));
                   6210:                         }
                   6211:                     }
                   6212:                 }
                   6213:             }
                   6214:         }
                   6215:     } else {
                   6216:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6217:         my $now = time;
1.1170    droeschl 6218: 
1.1172.2.58  raeburn  6219:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6220:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6221:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6222:                 return 1 unless ($tend && $tend < $now)
                   6223:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6224:             }
1.1172.2.23  raeburn  6225:         }
                   6226:     }
1.461     www      6227:     return 0;
1.9       www      6228: }
1.1       albertel 6229: 
1.1172.2.23  raeburn  6230: sub privileged_by_domain {
                   6231:     my ($domains,$roles) = @_;
                   6232:     my %privileged = ();
                   6233:     my $cachetime = 60*60*24;
                   6234:     my $now = time;
                   6235:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6236:         return %privileged;
                   6237:     }
                   6238:     foreach my $dom (@{$domains}) {
                   6239:         next if (ref($privileged{$dom}) eq 'HASH');
                   6240:         my $needroles;
                   6241:         foreach my $role (@{$roles}) {
                   6242:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6243:             if (defined($cached)) {
                   6244:                 if (ref($result) eq 'HASH') {
                   6245:                     $privileged{$dom}{$role} = $result;
                   6246:                 }
                   6247:             } else {
                   6248:                 $needroles = 1;
                   6249:             }
                   6250:         }
                   6251:         if ($needroles) {
                   6252:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6253:             $privileged{$dom} = {};
                   6254:             foreach my $server (keys(%dompersonnel)) {
                   6255:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6256:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6257:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6258:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6259:                         next if ($end && $end < $now);
                   6260:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6261:                             $dompersonnel{$server}{$item};
                   6262:                     }
                   6263:                 }
                   6264:             }
                   6265:             if (ref($privileged{$dom}) eq 'HASH') {
                   6266:                 foreach my $role (@{$roles}) {
                   6267:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6268:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6269:                     } else {
                   6270:                         my %hash = ();
                   6271:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6272:                     }
                   6273:                 }
                   6274:             }
                   6275:         }
                   6276:     }
                   6277:     return %privileged;
                   6278: }
                   6279: 
1.103     harris41 6280: # -------------------------------------------------------- Get user privileges
1.11      www      6281: 
                   6282: sub rolesinit {
1.1169    droeschl 6283:     my ($domain, $username) = @_;
                   6284:     my %userroles = ('user.login.time' => time);
                   6285:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6286: 
                   6287:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6288:     # also, blocking can be triggered by an activating timer
                   6289:     # it's saved in the user's %env.
                   6290:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6291:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6292:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6293:         %timerintchk, %timerintenv);
                   6294: 
1.1162    raeburn  6295:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6296:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6297:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6298:     }
1.1169    droeschl 6299: 
1.1162    raeburn  6300:     foreach my $key (keys(%timerinterval)) {
                   6301:         my ($cid,$rest) = split(/\0/,$key);
                   6302:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6303:     }
1.1169    droeschl 6304: 
1.11      www      6305:     my %allroles=();
1.1162    raeburn  6306:     my %allgroups=();
1.11      www      6307: 
1.1172.2.58  raeburn  6308:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6309:         my $role = $rolesdump{$area};
                   6310:         $area =~ s/\_\w\w$//;
                   6311: 
                   6312:         my ($trole, $tend, $tstart, $group_privs);
                   6313: 
                   6314:         if ($role =~ /^cr/) {
                   6315:         # Custom role, defined by a user 
                   6316:         # e.g., user.role.cr/msu/smith/mynewrole
                   6317:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6318:                 $trole = $1;
                   6319:                 ($tend, $tstart) = split('_', $2);
                   6320:             } else {
                   6321:                 $trole = $role;
                   6322:             }
                   6323:         } elsif ($role =~ m|^gr/|) {
                   6324:         # Role of member in a group, defined within a course/community
                   6325:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6326:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6327:             next if $tstart eq '-1';
                   6328:             ($trole, $group_privs) = split(/\//, $trole);
                   6329:             $group_privs = &unescape($group_privs);
                   6330:         } else {
                   6331:         # Just a normal role, defined in roles.tab
                   6332:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6333:         }
                   6334: 
                   6335:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6336:                  $username);
                   6337:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6338: 
                   6339:         # role expired or not available yet?
                   6340:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6341:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6342: 
                   6343:         next if $area eq '' or $trole eq '';
                   6344: 
                   6345:         my $spec = "$trole.$area";
                   6346:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6347: 
                   6348:         if ($trole =~ /^cr\//) {
                   6349:         # Custom role, defined by a user
                   6350:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6351:         } elsif ($trole eq 'gr') {
                   6352:         # Role of a member in a group, defined within a course/community
                   6353:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6354:             next;
                   6355:         } else {
                   6356:         # Normal role, defined in roles.tab
                   6357:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6358:         }
                   6359: 
                   6360:         my $cid = $tdomain.'_'.$trest;
                   6361:         unless ($firstaccchk{$cid}) {
                   6362:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6363:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6364:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6365:                         $coursetimerstarts{$cid}{$item}; 
                   6366:                 }
                   6367:             }
                   6368:             $firstaccchk{$cid} = 1;
                   6369:         }
                   6370:         unless ($timerintchk{$cid}) {
                   6371:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6372:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6373:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6374:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6375:                 }
1.12      www      6376:             }
1.1169    droeschl 6377:             $timerintchk{$cid} = 1;
1.191     harris41 6378:         }
1.11      www      6379:     }
1.1169    droeschl 6380: 
1.1172.2.91  raeburn  6381:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6382:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6383:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6384:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6385: 
1.1162    raeburn  6386:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6387: }
                   6388: 
1.567     raeburn  6389: sub set_arearole {
1.1172.2.19  raeburn  6390:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6391:     unless ($nolog) {
1.567     raeburn  6392: # log the associated role with the area
1.1172.2.19  raeburn  6393:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6394:     }
1.743     albertel 6395:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6396: }
                   6397: 
                   6398: sub custom_roleprivs {
                   6399:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6400:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6401:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6402:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6403:         my ($rdummy,$roledef)=
                   6404:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6405:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6406:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6407:             if (defined($syspriv)) {
1.1043    raeburn  6408:                 if ($trest =~ /^$match_community$/) {
                   6409:                     $syspriv =~ s/bre\&S//; 
                   6410:                 }
1.567     raeburn  6411:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6412:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6413:             }
                   6414:             if ($tdomain ne '') {
                   6415:                 if (defined($dompriv)) {
                   6416:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6417:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6418:                 }
                   6419:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6420:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6421:                         my $rolename = $1;
                   6422:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6423:                     }
1.567     raeburn  6424:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6425:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6426:                 }
                   6427:             }
                   6428:         }
                   6429:     }
                   6430: }
                   6431: 
1.1172.2.89  raeburn  6432: sub course_adhocrole_privs {
                   6433:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6434:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6435:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6436:         my (%currprivs,%storeprivs);
                   6437:         foreach my $item (split(/:/,$coursepriv)) {
                   6438:             my ($priv,$restrict) = split(/\&/,$item);
                   6439:             $currprivs{$priv} = $restrict;
                   6440:         }
                   6441:         my (%possadd,%possremove,%full);
                   6442:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6443:             my ($priv,$restrict)=split(/\&/,$item);
                   6444:             $full{$priv} = $restrict;
                   6445:         }
                   6446:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6447:              next if ($item eq '');
                   6448:              my ($rule,$rest) = split(/=/,$item);
                   6449:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6450:              foreach my $priv (split(/:/,$rest)) {
                   6451:                  if ($priv ne '') {
                   6452:                      if ($rule eq 'off') {
                   6453:                          $possremove{$priv} = 1;
                   6454:                      } else {
                   6455:                          $possadd{$priv} = 1;
                   6456:                      }
                   6457:                  }
                   6458:              }
                   6459:          }
                   6460:          foreach my $priv (sort(keys(%full))) {
                   6461:              if (exists($currprivs{$priv})) {
                   6462:                  unless (exists($possremove{$priv})) {
                   6463:                      $storeprivs{$priv} = $currprivs{$priv};
                   6464:                  }
                   6465:              } elsif (exists($possadd{$priv})) {
                   6466:                  $storeprivs{$priv} = $full{$priv};
                   6467:              }
                   6468:          }
                   6469:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6470:      }
                   6471:      return $coursepriv;
                   6472: }
                   6473: 
1.678     raeburn  6474: sub group_roleprivs {
                   6475:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6476:     my $access = 1;
                   6477:     my $now = time;
                   6478:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6479:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6480:     if ($access) {
1.811     albertel 6481:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6482:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6483:     }
                   6484: }
1.567     raeburn  6485: 
                   6486: sub standard_roleprivs {
                   6487:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6488:     if (defined($pr{$trole.':s'})) {
                   6489:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6490:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6491:     }
                   6492:     if ($tdomain ne '') {
                   6493:         if (defined($pr{$trole.':d'})) {
                   6494:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6495:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6496:         }
                   6497:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6498:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6499:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6500:         }
                   6501:     }
                   6502: }
                   6503: 
                   6504: sub set_userprivs {
1.1064    raeburn  6505:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6506:     my $author=0;
                   6507:     my $adv=0;
1.1172.2.91  raeburn  6508:     my $rar=0;
1.678     raeburn  6509:     my %grouproles = ();
                   6510:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6511:         my @groupkeys; 
1.1000    raeburn  6512:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6513:             push(@groupkeys,$role);
                   6514:         }
                   6515:         if (ref($groups_roles) eq 'HASH') {
                   6516:             foreach my $key (keys(%{$groups_roles})) {
                   6517:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6518:                     push(@groupkeys,$key);
                   6519:                 }
                   6520:             }
                   6521:         }
                   6522:         if (@groupkeys > 0) {
                   6523:             foreach my $role (@groupkeys) {
                   6524:                 my ($trole,$area,$sec,$extendedarea);
                   6525:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6526:                     $trole = $1;
                   6527:                     $area = $2;
                   6528:                     $sec = $3;
                   6529:                     $extendedarea = $area.$sec;
                   6530:                     if (exists($$allgroups{$area})) {
                   6531:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6532:                             my $spec = $trole.'.'.$extendedarea;
                   6533:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6534:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6535:                         }
1.678     raeburn  6536:                     }
                   6537:                 }
                   6538:             }
                   6539:         }
                   6540:     }
1.800     albertel 6541:     foreach my $group (keys(%grouproles)) {
                   6542:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6543:     }
1.800     albertel 6544:     foreach my $role (keys(%{$allroles})) {
                   6545:         my %thesepriv;
1.941     raeburn  6546:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6547:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6548:             if ($item ne '') {
                   6549:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6550:                 if ($restrictions eq '') {
                   6551:                     $thesepriv{$privilege}='F';
                   6552:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6553:                     $thesepriv{$privilege}.=$restrictions;
                   6554:                 }
                   6555:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6556:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6557:             }
                   6558:         }
                   6559:         my $thesestr='';
1.1104    raeburn  6560:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6561: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6562: 	}
                   6563:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6564:     }
1.1172.2.91  raeburn  6565:     return ($author,$adv,$rar);
1.567     raeburn  6566: }
                   6567: 
1.994     raeburn  6568: sub role_status {
1.1104    raeburn  6569:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6570:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6571:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6572:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6573:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6574:             $$where = '/'.$two;
1.994     raeburn  6575:             $$trolecode=$$role.'.'.$$where;
                   6576:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6577:             $$tstatus='is';
1.1104    raeburn  6578:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6579:                 $$tstatus='future';
1.1034    raeburn  6580:                 if ($$tstart<$now) {
                   6581:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6582:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6583:                             my (%allroles,%allgroups,$group_privs,
                   6584:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6585:                             my %userroles = (
                   6586:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6587:                             );
1.1064    raeburn  6588:                             @rolecodes = ('cm'); 
1.1002    raeburn  6589:                             my $spec=$$role.'.'.$$where;
                   6590:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6591:                             if ($$role =~ /^cr\//) {
                   6592:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6593:                                 push(@rolecodes,'cr');
1.1002    raeburn  6594:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6595:                                 push(@rolecodes,$$role);
1.1002    raeburn  6596:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6597:                                                     $env{'user.name'});
1.1064    raeburn  6598:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6599:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6600:                                 $group_privs = &unescape($group_privs);
                   6601:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6602:                                 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  6603:                                 &get_groups_roles($tdomain,$trest,
                   6604:                                                   \%course_roles,\@rolecodes,
                   6605:                                                   \%groups_roles);
1.1002    raeburn  6606:                             } else {
1.1064    raeburn  6607:                                 push(@rolecodes,$$role);
1.1002    raeburn  6608:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6609:                             }
1.1172.2.91  raeburn  6610:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6611:                                                                    \%groups_roles);
1.1064    raeburn  6612:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6613:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6614:                         }
                   6615:                     }
1.1034    raeburn  6616:                     $$tstatus = 'is';
1.1002    raeburn  6617:                 }
1.994     raeburn  6618:             }
                   6619:             if ($$tend) {
1.1104    raeburn  6620:                 if ($$tend<$update) {
1.994     raeburn  6621:                     $$tstatus='expired';
                   6622:                 } elsif ($$tend<$now) {
                   6623:                     $$tstatus='will_not';
                   6624:                 }
                   6625:             }
                   6626:         }
                   6627:     }
                   6628: }
                   6629: 
1.1104    raeburn  6630: sub get_groups_roles {
                   6631:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6632:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6633:                   (ref($rolecodes) eq 'ARRAY') && 
                   6634:                   (ref($groups_roles) eq 'HASH')); 
                   6635:     if (keys(%{$cdom_courseroles}) > 0) {
                   6636:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6637:         if ($cdom ne '' && $cnum ne '') {
                   6638:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6639:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6640:                     my $crsrole = $1;
                   6641:                     my $crssec = $2;
                   6642:                     if ($crsrole =~ /^cr/) {
                   6643:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6644:                             push(@{$rolecodes},'cr');
                   6645:                         }
                   6646:                     } else {
                   6647:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6648:                             push(@{$rolecodes},$crsrole);
                   6649:                         }
                   6650:                     }
                   6651:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6652:                     if ($crssec ne '') {
                   6653:                         $rolekey .= "/$crssec";
                   6654:                     }
                   6655:                     $rolekey .= './';
                   6656:                     $groups_roles->{$rolekey} = $rolecodes;
                   6657:                 }
                   6658:             }
                   6659:         }
                   6660:     }
                   6661:     return;
                   6662: }
                   6663: 
                   6664: sub delete_env_groupprivs {
                   6665:     my ($where,$courseroles,$possroles) = @_;
                   6666:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6667:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6668:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6669:         %{$courseroles->{$udom}} =
                   6670:             &get_my_roles('','','userroles',['active'],
                   6671:                           $possroles,[$udom],1);
                   6672:     }
                   6673:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6674:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6675:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6676:             my $area = '/'.$cdom.'/'.$cnum;
                   6677:             my $privkey = "user.priv.$crsrole.$area";
                   6678:             if ($crssec ne '') {
                   6679:                 $privkey .= '/'.$crssec;
                   6680:             }
                   6681:             $privkey .= ".$area/$group";
                   6682:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6683:         }
                   6684:     }
                   6685:     return;
                   6686: }
                   6687: 
1.994     raeburn  6688: sub check_adhoc_privs {
1.1172.2.86  raeburn  6689:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6690:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6691:     if ($sec) {
                   6692:         $cckey .= '/'.$sec;
                   6693:     }
1.1172.2.9  raeburn  6694:     my $setprivs;
1.994     raeburn  6695:     if ($env{$cckey}) {
                   6696:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6697:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6698:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6699:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6700:             $setprivs = 1;
1.994     raeburn  6701:         }
                   6702:     } else {
1.1172.2.87  raeburn  6703:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6704:         $setprivs = 1;
1.994     raeburn  6705:     }
1.1172.2.9  raeburn  6706:     return $setprivs;
1.994     raeburn  6707: }
                   6708: 
                   6709: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6710: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6711:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6712:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6713:     if ($sec ne '') {
                   6714:         $area .= '/'.$sec;
                   6715:     }
1.994     raeburn  6716:     my $spec = $role.'.'.$area;
                   6717:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6718:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6719:     my %rolehash = ();
1.1172.2.89  raeburn  6720:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6721:         my $rolename = $1;
1.1172.2.84  raeburn  6722:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6723:         my %domdef = &get_domain_defaults($dcdom);
                   6724:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6725:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6726:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6727:             }
                   6728:         }
1.1172.2.84  raeburn  6729:     } else {
                   6730:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6731:     }
1.1172.2.91  raeburn  6732:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6733:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6734:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6735:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6736:         &appenv( {'request.role'        => $spec,
                   6737:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6738:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6739:                  }
                   6740:                );
                   6741:         my $tadv=0;
                   6742:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6743:         &appenv({'request.role.adv'    => $tadv});
                   6744:     }
1.994     raeburn  6745: }
                   6746: 
1.12      www      6747: # --------------------------------------------------------------- get interface
                   6748: 
                   6749: sub get {
1.131     albertel 6750:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6751:    my $items='';
1.800     albertel 6752:    foreach my $item (@$storearr) {
                   6753:        $items.=&escape($item).'&';
1.191     harris41 6754:    }
1.12      www      6755:    $items=~s/\&$//;
1.620     albertel 6756:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6757:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6758:    my $uhome=&homeserver($uname,$udomain);
                   6759: 
1.133     albertel 6760:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6761:    my @pairs=split(/\&/,$rep);
1.273     albertel 6762:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6763:      return @pairs;
                   6764:    }
1.15      www      6765:    my %returnhash=();
1.42      www      6766:    my $i=0;
1.800     albertel 6767:    foreach my $item (@$storearr) {
                   6768:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6769:       $i++;
1.191     harris41 6770:    }
1.15      www      6771:    return %returnhash;
1.27      www      6772: }
                   6773: 
                   6774: # --------------------------------------------------------------- del interface
                   6775: 
                   6776: sub del {
1.133     albertel 6777:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6778:    my $items='';
1.800     albertel 6779:    foreach my $item (@$storearr) {
                   6780:        $items.=&escape($item).'&';
1.191     harris41 6781:    }
1.984     neumanie 6782: 
1.27      www      6783:    $items=~s/\&$//;
1.620     albertel 6784:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6785:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6786:    my $uhome=&homeserver($uname,$udomain);
                   6787:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6788: }
                   6789: 
                   6790: # -------------------------------------------------------------- dump interface
                   6791: 
1.1172.2.22  raeburn  6792: sub unserialize {
                   6793:     my ($rep, $escapedkeys) = @_;
                   6794: 
                   6795:     return {} if $rep =~ /^error/;
                   6796: 
                   6797:     my %returnhash=();
                   6798:     foreach my $item (split(/\&/,$rep)) {
                   6799:         my ($key, $value) = split(/=/, $item, 2);
                   6800:         $key = unescape($key) unless $escapedkeys;
                   6801:         next if $key =~ /^error: 2 /;
                   6802:         $returnhash{$key} = &thaw_unescape($value);
                   6803:     }
                   6804:     return \%returnhash;
                   6805: }
                   6806: 
                   6807: # see Lond::dump_with_regexp
                   6808: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6809: sub dump {
1.1172.2.22  raeburn  6810:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6811:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6812:     if (!$uname) { $uname=$env{'user.name'}; }
                   6813:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6814: 
1.1172.2.55  raeburn  6815:     if ($regexp) {
                   6816:         $regexp=&escape($regexp);
                   6817:     } else {
                   6818:         $regexp='.';
                   6819:     }
1.1172.2.22  raeburn  6820:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6821:         # user is hosted on this machine
1.1172.2.55  raeburn  6822:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6823:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6824:         return %{&unserialize($reply, $escapedkeys)};
                   6825:     }
1.1166    raeburn  6826:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6827:     my @pairs=split(/\&/,$rep);
                   6828:     my %returnhash=();
1.1098    foxr     6829:     if (!($rep =~ /^error/ )) {
                   6830: 	foreach my $item (@pairs) {
                   6831: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6832:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6833: 	    next if ($key =~ /^error: 2 /);
                   6834: 	    $returnhash{$key}=&thaw_unescape($value);
                   6835: 	}
1.755     albertel 6836:     }
                   6837:     return %returnhash;
1.407     www      6838: }
                   6839: 
1.1098    foxr     6840: 
1.717     albertel 6841: # --------------------------------------------------------- dumpstore interface
                   6842: 
                   6843: sub dumpstore {
                   6844:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6845:    # same as dump but keys must be escaped. They may contain colon separated
                   6846:    # lists of values that may themself contain colons (e.g. symbs).
                   6847:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6848: }
                   6849: 
1.407     www      6850: # -------------------------------------------------------------- keys interface
                   6851: 
                   6852: sub getkeys {
                   6853:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6854:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6855:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6856:    my $uhome=&homeserver($uname,$udomain);
                   6857:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6858:    my @keyarray=();
1.800     albertel 6859:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6860:       next if ($key =~ /^error: 2 /);
1.800     albertel 6861:       push(@keyarray,&unescape($key));
1.407     www      6862:    }
                   6863:    return @keyarray;
1.318     matthew  6864: }
                   6865: 
1.319     matthew  6866: # --------------------------------------------------------------- currentdump
                   6867: sub currentdump {
1.328     matthew  6868:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6869:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6870:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6871:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6872:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6873:    my $rep;
                   6874: 
                   6875:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6876:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6877:                    $courseid)));
                   6878:    } else {
                   6879:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6880:    }
                   6881: 
1.318     matthew  6882:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6883:    #
1.318     matthew  6884:    my %returnhash=();
1.319     matthew  6885:    #
                   6886:    if ($rep eq "unknown_cmd") { 
                   6887:        # an old lond will not know currentdump
                   6888:        # Do a dump and make it look like a currentdump
1.822     albertel 6889:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6890:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6891:        my %hash = @tmp;
                   6892:        @tmp=();
1.424     matthew  6893:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6894:    } else {
                   6895:        my @pairs=split(/\&/,$rep);
1.800     albertel 6896:        foreach my $pair (@pairs) {
                   6897:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6898:            my ($symb,$param) = split(/:/,$key);
                   6899:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6900:                                                         &thaw_unescape($value);
1.319     matthew  6901:        }
1.191     harris41 6902:    }
1.12      www      6903:    return %returnhash;
1.424     matthew  6904: }
                   6905: 
                   6906: sub convert_dump_to_currentdump{
                   6907:     my %hash = %{shift()};
                   6908:     my %returnhash;
                   6909:     # Code ripped from lond, essentially.  The only difference
                   6910:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6911:     # we might run in to problems with parameter names =~ /^v\./
                   6912:     while (my ($key,$value) = each(%hash)) {
                   6913:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6914: 	$symb  = &unescape($symb);
                   6915: 	$param = &unescape($param);
1.424     matthew  6916:         next if ($v eq 'version' || $symb eq 'keys');
                   6917:         next if (exists($returnhash{$symb}) &&
                   6918:                  exists($returnhash{$symb}->{$param}) &&
                   6919:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6920:         $returnhash{$symb}->{$param}=$value;
                   6921:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6922:     }
                   6923:     #
                   6924:     # Remove all of the keys in the hashes which keep track of
                   6925:     # the version of the parameter.
                   6926:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6927:         # use a foreach because we are going to delete from the hash.
                   6928:         foreach my $key (keys(%$param_hash)) {
                   6929:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6930:         }
                   6931:     }
                   6932:     return \%returnhash;
1.12      www      6933: }
                   6934: 
1.627     albertel 6935: # ------------------------------------------------------ critical inc interface
                   6936: 
                   6937: sub cinc {
                   6938:     return &inc(@_,'critical');
                   6939: }
                   6940: 
1.449     matthew  6941: # --------------------------------------------------------------- inc interface
                   6942: 
                   6943: sub inc {
1.627     albertel 6944:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6945:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6946:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6947:     my $uhome=&homeserver($uname,$udomain);
                   6948:     my $items='';
                   6949:     if (! ref($store)) {
                   6950:         # got a single value, so use that instead
                   6951:         $items = &escape($store).'=&';
                   6952:     } elsif (ref($store) eq 'SCALAR') {
                   6953:         $items = &escape($$store).'=&';        
                   6954:     } elsif (ref($store) eq 'ARRAY') {
                   6955:         $items = join('=&',map {&escape($_);} @{$store});
                   6956:     } elsif (ref($store) eq 'HASH') {
                   6957:         while (my($key,$value) = each(%{$store})) {
                   6958:             $items.= &escape($key).'='.&escape($value).'&';
                   6959:         }
                   6960:     }
                   6961:     $items=~s/\&$//;
1.627     albertel 6962:     if ($critical) {
                   6963: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6964:     } else {
                   6965: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6966:     }
1.449     matthew  6967: }
                   6968: 
1.12      www      6969: # --------------------------------------------------------------- put interface
                   6970: 
                   6971: sub put {
1.134     albertel 6972:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6973:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6974:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6975:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6976:    my $items='';
1.800     albertel 6977:    foreach my $item (keys(%$storehash)) {
                   6978:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6979:    }
1.12      www      6980:    $items=~s/\&$//;
1.134     albertel 6981:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6982: }
                   6983: 
1.631     albertel 6984: # ------------------------------------------------------------ newput interface
                   6985: 
                   6986: sub newput {
                   6987:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6988:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6989:    if (!$uname) { $uname=$env{'user.name'}; }
                   6990:    my $uhome=&homeserver($uname,$udomain);
                   6991:    my $items='';
                   6992:    foreach my $key (keys(%$storehash)) {
                   6993:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6994:    }
                   6995:    $items=~s/\&$//;
                   6996:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6997: }
                   6998: 
                   6999: # ---------------------------------------------------------  putstore interface
                   7000: 
1.524     raeburn  7001: sub putstore {
1.1172.2.59  raeburn  7002:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7003:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7004:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7005:    my $uhome=&homeserver($uname,$udomain);
                   7006:    my $items='';
1.715     albertel 7007:    foreach my $key (keys(%$storehash)) {
                   7008:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7009:    }
1.715     albertel 7010:    $items=~s/\&$//;
1.716     albertel 7011:    my $esc_symb=&escape($symb);
                   7012:    my $esc_v=&escape($version);
1.715     albertel 7013:    my $reply =
1.716     albertel 7014:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7015: 	      $uhome);
1.1172.2.59  raeburn  7016:    if (($tolog) && ($reply eq 'ok')) {
                   7017:        my $namevalue='';
                   7018:        foreach my $key (keys(%{$storehash})) {
                   7019:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7020:        }
                   7021:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7022:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7023:                      '&version='.$esc_v.
                   7024:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7025:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7026:    }
1.715     albertel 7027:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7028:        # gfall back to way things use to be done
1.715     albertel 7029:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7030: 			    $uname);
1.524     raeburn  7031:    }
1.715     albertel 7032:    return $reply;
                   7033: }
                   7034: 
                   7035: sub old_putstore {
1.716     albertel 7036:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7037:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7038:     if (!$uname) { $uname=$env{'user.name'}; }
                   7039:     my $uhome=&homeserver($uname,$udomain);
                   7040:     my %newstorehash;
1.800     albertel 7041:     foreach my $item (keys(%$storehash)) {
                   7042: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7043: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7044:     }
                   7045:     my $items='';
                   7046:     my %allitems = ();
1.800     albertel 7047:     foreach my $item (keys(%newstorehash)) {
                   7048: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7049: 	    my $key = $1.':keys:'.$2;
                   7050: 	    $allitems{$key} .= $3.':';
                   7051: 	}
1.800     albertel 7052: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7053:     }
1.800     albertel 7054:     foreach my $item (keys(%allitems)) {
                   7055: 	$allitems{$item} =~ s/\:$//;
                   7056: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7057:     }
                   7058:     $items=~s/\&$//;
                   7059:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7060: }
                   7061: 
1.47      www      7062: # ------------------------------------------------------ critical put interface
                   7063: 
                   7064: sub cput {
1.134     albertel 7065:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7067:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7068:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7069:    my $items='';
1.800     albertel 7070:    foreach my $item (keys(%$storehash)) {
                   7071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7072:    }
1.47      www      7073:    $items=~s/\&$//;
1.134     albertel 7074:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7075: }
                   7076: 
                   7077: # -------------------------------------------------------------- eget interface
                   7078: 
                   7079: sub eget {
1.133     albertel 7080:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7081:    my $items='';
1.800     albertel 7082:    foreach my $item (@$storearr) {
                   7083:        $items.=&escape($item).'&';
1.191     harris41 7084:    }
1.12      www      7085:    $items=~s/\&$//;
1.620     albertel 7086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7087:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7088:    my $uhome=&homeserver($uname,$udomain);
                   7089:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7090:    my @pairs=split(/\&/,$rep);
                   7091:    my %returnhash=();
1.42      www      7092:    my $i=0;
1.800     albertel 7093:    foreach my $item (@$storearr) {
                   7094:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7095:       $i++;
1.191     harris41 7096:    }
1.12      www      7097:    return %returnhash;
                   7098: }
                   7099: 
1.667     albertel 7100: # ------------------------------------------------------------ tmpput interface
                   7101: sub tmpput {
1.802     raeburn  7102:     my ($storehash,$server,$context)=@_;
1.667     albertel 7103:     my $items='';
1.800     albertel 7104:     foreach my $item (keys(%$storehash)) {
                   7105: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7106:     }
                   7107:     $items=~s/\&$//;
1.802     raeburn  7108:     if (defined($context)) {
                   7109:         $items .= ':'.&escape($context);
                   7110:     }
1.667     albertel 7111:     return &reply("tmpput:$items",$server);
                   7112: }
                   7113: 
                   7114: # ------------------------------------------------------------ tmpget interface
                   7115: sub tmpget {
1.688     albertel 7116:     my ($token,$server)=@_;
                   7117:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7118:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7119:     my %returnhash;
1.1172.2.85  raeburn  7120:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7121:         return %returnhash;
                   7122:     }
1.667     albertel 7123:     foreach my $item (split(/\&/,$rep)) {
                   7124: 	my ($key,$value)=split(/=/,$item);
                   7125: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7126:     }
                   7127:     return %returnhash;
                   7128: }
                   7129: 
1.1113    raeburn  7130: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7131: sub tmpdel {
                   7132:     my ($token,$server)=@_;
                   7133:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7134:     return &reply("tmpdel:$token",$server);
                   7135: }
                   7136: 
1.1172.2.13  raeburn  7137: # ------------------------------------------------------------ get_timebased_id
                   7138: 
                   7139: sub get_timebased_id {
                   7140:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7141:         $maxtries) = @_;
                   7142:     my ($newid,$error,$dellock);
                   7143:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7144:         return ('','ok','invalid call to get suffix');
                   7145:     }
                   7146: 
                   7147: # set defaults for any optional args for which values were not supplied
                   7148:     if ($who eq '') {
                   7149:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7150:     }
                   7151:     if (!$locktries) {
                   7152:         $locktries = 3;
                   7153:     }
                   7154:     if (!$maxtries) {
                   7155:         $maxtries = 10;
                   7156:     }
                   7157: 
                   7158:     if (($cdom eq '') || ($cnum eq '')) {
                   7159:         if ($env{'request.course.id'}) {
                   7160:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7161:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7162:         }
                   7163:         if (($cdom eq '') || ($cnum eq '')) {
                   7164:             return ('','ok','call to get suffix not in course context');
                   7165:         }
                   7166:     }
                   7167: 
                   7168: # construct locking item
                   7169:     my $lockhash = {
                   7170:                       $prefix."\0".'locked_'.$keyid => $who,
                   7171:                    };
                   7172:     my $tries = 0;
                   7173: 
                   7174: # attempt to get lock on nohist_$namespace file
                   7175:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7176:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7177:         $tries ++;
                   7178:         sleep 1;
                   7179:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7180:     }
                   7181: 
                   7182: # attempt to get unique identifier, based on current timestamp
                   7183:     if ($gotlock eq 'ok') {
                   7184:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7185:         my $id = time;
                   7186:         $newid = $id;
1.1172.2.56  raeburn  7187:         if ($idtype eq 'addcode') {
                   7188:             $newid .= &sixnum_code();
                   7189:         }
1.1172.2.13  raeburn  7190:         my $idtries = 0;
                   7191:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7192:             if ($idtype eq 'concat') {
                   7193:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7194:             } elsif ($idtype eq 'addcode') {
                   7195:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7196:             } else {
                   7197:                 $newid ++;
                   7198:             }
                   7199:             $idtries ++;
                   7200:         }
                   7201:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7202:             my %new_item =  (
                   7203:                               $prefix."\0".$newid => $who,
                   7204:                             );
                   7205:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7206:                                                  $cdom,$cnum);
                   7207:             if ($putresult ne 'ok') {
                   7208:                 undef($newid);
                   7209:                 $error = 'error saving new item: '.$putresult;
                   7210:             }
                   7211:         } else {
1.1172.2.56  raeburn  7212:              undef($newid);
1.1172.2.13  raeburn  7213:              $error = ('error: no unique suffix available for the new item ');
                   7214:         }
                   7215: #  remove lock
                   7216:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7217:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7218:     } else {
                   7219:         $error = "error: could not obtain lockfile\n";
                   7220:         $dellock = 'ok';
1.1172.2.58  raeburn  7221:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7222:             $dellock = 'nolock';
                   7223:         }
1.1172.2.13  raeburn  7224:     }
                   7225:     return ($newid,$dellock,$error);
                   7226: }
                   7227: 
1.1172.2.56  raeburn  7228: sub sixnum_code {
                   7229:     my $code;
                   7230:     for (0..6) {
                   7231:         $code .= int( rand(9) );
                   7232:     }
                   7233:     return $code;
                   7234: }
                   7235: 
1.765     albertel 7236: # -------------------------------------------------- portfolio access checking
                   7237: 
                   7238: sub portfolio_access {
1.1172.2.77  raeburn  7239:     my ($requrl,$clientip) = @_;
1.765     albertel 7240:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7241:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7242:     if ($result) {
                   7243:         my %setters;
                   7244:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7245:             my ($startblock,$endblock) =
                   7246:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7247:             if ($startblock && $endblock) {
                   7248:                 return 'B';
                   7249:             }
                   7250:         } else {
                   7251:             my ($startblock,$endblock) =
                   7252:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7253:             if ($startblock && $endblock) {
                   7254:                 return 'B';
                   7255:             }
                   7256:         }
                   7257:     }
1.765     albertel 7258:     if ($result eq 'ok') {
1.766     albertel 7259:        return 'F';
1.765     albertel 7260:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7261:        return 'A';
1.765     albertel 7262:     }
1.766     albertel 7263:     return '';
1.765     albertel 7264: }
                   7265: 
                   7266: sub get_portfolio_access {
1.1172.2.77  raeburn  7267:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7268: 
                   7269:     if (!ref($access_hash)) {
                   7270: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7271: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7272: 						   $file_name);
                   7273: 	$access_hash = $access_controls{$file_name};
                   7274:     }
                   7275: 
1.1172.2.77  raeburn  7276:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7277:     my $now = time;
                   7278:     if (ref($access_hash) eq 'HASH') {
                   7279:         foreach my $key (keys(%{$access_hash})) {
                   7280:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7281:             if ($start > $now) {
                   7282:                 next;
                   7283:             }
                   7284:             if ($end && $end<$now) {
                   7285:                 next;
                   7286:             }
                   7287:             if ($scope eq 'public') {
                   7288:                 $public = $key;
                   7289:                 last;
                   7290:             } elsif ($scope eq 'guest') {
                   7291:                 $guest = $key;
                   7292:             } elsif ($scope eq 'domains') {
                   7293:                 push(@domains,$key);
                   7294:             } elsif ($scope eq 'users') {
                   7295:                 push(@users,$key);
                   7296:             } elsif ($scope eq 'course') {
                   7297:                 push(@courses,$key);
                   7298:             } elsif ($scope eq 'group') {
                   7299:                 push(@groups,$key);
1.1172.2.77  raeburn  7300:             } elsif ($scope eq 'ip') {
                   7301:                 push(@ips,$key);
1.765     albertel 7302:             }
                   7303:         }
                   7304:         if ($public) {
                   7305:             return 'ok';
1.1172.2.77  raeburn  7306:         } elsif (@ips > 0) {
                   7307:             my $allowed;
                   7308:             foreach my $ipkey (@ips) {
                   7309:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7310:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7311:                         $allowed = 1;
                   7312:                         last;
                   7313:                     }
                   7314:                 }
                   7315:             }
                   7316:             if ($allowed) {
                   7317:                 return 'ok';
                   7318:             }
1.765     albertel 7319:         }
                   7320:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7321:             if ($guest) {
                   7322:                 return $guest;
                   7323:             }
                   7324:         } else {
                   7325:             if (@domains > 0) {
                   7326:                 foreach my $domkey (@domains) {
                   7327:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7328:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7329:                             return 'ok';
                   7330:                         }
                   7331:                     }
                   7332:                 }
                   7333:             }
                   7334:             if (@users > 0) {
                   7335:                 foreach my $userkey (@users) {
1.865     raeburn  7336:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7337:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7338:                             if (ref($item) eq 'HASH') {
                   7339:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7340:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7341:                                     return 'ok';
                   7342:                                 }
                   7343:                             }
                   7344:                         }
                   7345:                     } 
1.765     albertel 7346:                 }
                   7347:             }
                   7348:             my %roleshash;
                   7349:             my @courses_and_groups = @courses;
                   7350:             push(@courses_and_groups,@groups); 
                   7351:             if (@courses_and_groups > 0) {
                   7352:                 my (%allgroups,%allroles); 
                   7353:                 my ($start,$end,$role,$sec,$group);
                   7354:                 foreach my $envkey (%env) {
1.1060    raeburn  7355:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7356:                         my $cid = $2.'_'.$3; 
                   7357:                         if ($1 eq 'gr') {
                   7358:                             $group = $4;
                   7359:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7360:                         } else {
                   7361:                             if ($4 eq '') {
                   7362:                                 $sec = 'none';
                   7363:                             } else {
                   7364:                                 $sec = $4;
                   7365:                             }
                   7366:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7367:                         }
1.811     albertel 7368:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7369:                         my $cid = $2.'_'.$3;
                   7370:                         if ($4 eq '') {
                   7371:                             $sec = 'none';
                   7372:                         } else {
                   7373:                             $sec = $4;
                   7374:                         }
                   7375:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7376:                     }
                   7377:                 }
                   7378:                 if (keys(%allroles) == 0) {
                   7379:                     return;
                   7380:                 }
                   7381:                 foreach my $key (@courses_and_groups) {
                   7382:                     my %content = %{$$access_hash{$key}};
                   7383:                     my $cnum = $content{'number'};
                   7384:                     my $cdom = $content{'domain'};
                   7385:                     my $cid = $cdom.'_'.$cnum;
                   7386:                     if (!exists($allroles{$cid})) {
                   7387:                         next;
                   7388:                     }    
                   7389:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7390:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7391:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7392:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7393:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7394:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7395:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7396:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7397:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7398:                                         if (grep/^all$/,@sections) {
                   7399:                                             return 'ok';
                   7400:                                         } else {
                   7401:                                             if (grep/^$sec$/,@sections) {
                   7402:                                                 return 'ok';
                   7403:                                             }
                   7404:                                         }
                   7405:                                     }
                   7406:                                 }
                   7407:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7408:                                     if (grep/^none$/,@groups) {
                   7409:                                         return 'ok';
                   7410:                                     }
                   7411:                                 } else {
                   7412:                                     if (grep/^all$/,@groups) {
                   7413:                                         return 'ok';
                   7414:                                     } 
                   7415:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7416:                                         if (grep/^$group$/,@groups) {
                   7417:                                             return 'ok';
                   7418:                                         }
                   7419:                                     }
                   7420:                                 } 
                   7421:                             }
                   7422:                         }
                   7423:                     }
                   7424:                 }
                   7425:             }
                   7426:             if ($guest) {
                   7427:                 return $guest;
                   7428:             }
                   7429:         }
                   7430:     }
                   7431:     return;
                   7432: }
                   7433: 
                   7434: sub course_group_datechecker {
                   7435:     my ($dates,$now,$status) = @_;
                   7436:     my ($start,$end) = split(/\./,$dates);
                   7437:     if (!$start && !$end) {
                   7438:         return 'ok';
                   7439:     }
                   7440:     if (grep/^active$/,@{$status}) {
                   7441:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7442:             return 'ok';
                   7443:         }
                   7444:     }
                   7445:     if (grep/^previous$/,@{$status}) {
                   7446:         if ($end > $now ) {
                   7447:             return 'ok';
                   7448:         }
                   7449:     }
                   7450:     if (grep/^future$/,@{$status}) {
                   7451:         if ($start > $now) {
                   7452:             return 'ok';
                   7453:         }
                   7454:     }
                   7455:     return; 
                   7456: }
                   7457: 
                   7458: sub parse_portfolio_url {
                   7459:     my ($url) = @_;
                   7460: 
                   7461:     my ($type,$udom,$unum,$group,$file_name);
                   7462:     
1.823     albertel 7463:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7464: 	$type = 1;
                   7465:         $udom = $1;
                   7466:         $unum = $2;
                   7467:         $file_name = $3;
1.823     albertel 7468:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7469: 	$type = 2;
                   7470:         $udom = $1;
                   7471:         $unum = $2;
                   7472:         $group = $3;
                   7473:         $file_name = $3.'/'.$4;
                   7474:     }
                   7475:     if (wantarray) {
                   7476: 	return ($type,$udom,$unum,$file_name,$group);
                   7477:     }
                   7478:     return $type;
                   7479: }
                   7480: 
                   7481: sub is_portfolio_url {
                   7482:     my ($url) = @_;
                   7483:     return scalar(&parse_portfolio_url($url));
                   7484: }
                   7485: 
1.798     raeburn  7486: sub is_portfolio_file {
                   7487:     my ($file) = @_;
1.820     raeburn  7488:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7489:         return 1;
                   7490:     }
                   7491:     return;
                   7492: }
                   7493: 
1.976     raeburn  7494: sub usertools_access {
1.1084    raeburn  7495:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7496:     my ($access,%tools);
                   7497:     if ($context eq '') {
                   7498:         $context = 'tools';
                   7499:     }
                   7500:     if ($context eq 'requestcourses') {
                   7501:         %tools = (
                   7502:                       official   => 1,
                   7503:                       unofficial => 1,
1.1006    raeburn  7504:                       community  => 1,
1.1172.2.37  raeburn  7505:                       textbook   => 1,
1.985     raeburn  7506:                  );
1.1172.2.9  raeburn  7507:     } elsif ($context eq 'requestauthor') {
                   7508:         %tools = (
                   7509:                       requestauthor => 1,
                   7510:                  );
1.985     raeburn  7511:     } else {
                   7512:         %tools = (
                   7513:                       aboutme   => 1,
                   7514:                       blog      => 1,
1.1172.2.6  raeburn  7515:                       webdav    => 1,
1.985     raeburn  7516:                       portfolio => 1,
                   7517:                  );
                   7518:     }
1.976     raeburn  7519:     return if (!defined($tools{$tool}));
                   7520: 
1.1172.2.35  raeburn  7521:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7522:         $udom = $env{'user.domain'};
                   7523:         $uname = $env{'user.name'};
                   7524:     }
                   7525: 
1.978     raeburn  7526:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7527:         if ($action ne 'reload') {
1.985     raeburn  7528:             if ($context eq 'requestcourses') {
                   7529:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7530:             } elsif ($context eq 'requestauthor') {
                   7531:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7532:             } else {
                   7533:                 return $env{'environment.availabletools.'.$tool};
                   7534:             }
                   7535:         }
1.976     raeburn  7536:     }
                   7537: 
1.1172.2.9  raeburn  7538:     my ($toolstatus,$inststatus,$envkey);
                   7539:     if ($context eq 'requestauthor') {
                   7540:         $envkey = $context;
                   7541:     } else {
                   7542:         $envkey = $context.'.'.$tool;
                   7543:     }
1.976     raeburn  7544: 
1.985     raeburn  7545:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7546:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7547:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7548:         $inststatus = $env{'environment.inststatus'};
                   7549:     } else {
1.1084    raeburn  7550:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7551:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7552:             $inststatus = $userenvref->{'inststatus'};
                   7553:         } else {
1.1172.2.9  raeburn  7554:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7555:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7556:             $inststatus = $userenv{'inststatus'};
                   7557:         }
1.976     raeburn  7558:     }
                   7559: 
                   7560:     if ($toolstatus ne '') {
                   7561:         if ($toolstatus) {
                   7562:             $access = 1;
                   7563:         } else {
                   7564:             $access = 0;
                   7565:         }
                   7566:         return $access;
                   7567:     }
                   7568: 
1.1084    raeburn  7569:     my ($is_adv,%domdef);
                   7570:     if (ref($is_advref) eq 'HASH') {
                   7571:         $is_adv = $is_advref->{'is_adv'};
                   7572:     } else {
                   7573:         $is_adv = &is_advanced_user($udom,$uname);
                   7574:     }
                   7575:     if (ref($domdefref) eq 'HASH') {
                   7576:         %domdef = %{$domdefref};
                   7577:     } else {
                   7578:         %domdef = &get_domain_defaults($udom);
                   7579:     }
1.976     raeburn  7580:     if (ref($domdef{$tool}) eq 'HASH') {
                   7581:         if ($is_adv) {
                   7582:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7583:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7584:                     $access = 1;
                   7585:                 } else {
                   7586:                     $access = 0;
                   7587:                 }
                   7588:                 return $access;
                   7589:             }
                   7590:         }
                   7591:         if ($inststatus ne '') {
                   7592:             my ($hasaccess,$hasnoaccess);
                   7593:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7594:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7595:                     if ($domdef{$tool}{$affiliation}) {
                   7596:                         $hasaccess = 1;
                   7597:                     } else {
                   7598:                         $hasnoaccess = 1;
                   7599:                     }
                   7600:                 }
                   7601:             }
                   7602:             if ($hasaccess || $hasnoaccess) {
                   7603:                 if ($hasaccess) {
                   7604:                     $access = 1;
                   7605:                 } elsif ($hasnoaccess) {
                   7606:                     $access = 0; 
                   7607:                 }
                   7608:                 return $access;
                   7609:             }
                   7610:         } else {
                   7611:             if ($domdef{$tool}{'default'} ne '') {
                   7612:                 if ($domdef{$tool}{'default'}) {
                   7613:                     $access = 1;
                   7614:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7615:                     $access = 0;
                   7616:                 }
                   7617:                 return $access;
                   7618:             }
                   7619:         }
                   7620:     } else {
1.1172.2.6  raeburn  7621:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7622:             $access = 1;
                   7623:         } else {
                   7624:             $access = 0;
                   7625:         }
1.976     raeburn  7626:         return $access;
                   7627:     }
                   7628: }
                   7629: 
1.1050    raeburn  7630: sub is_course_owner {
                   7631:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7632:     if (($udom eq '') || ($uname eq '')) {
                   7633:         $udom = $env{'user.domain'};
                   7634:         $uname = $env{'user.name'};
                   7635:     }
                   7636:     unless (($udom eq '') || ($uname eq '')) {
                   7637:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7638:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7639:                 return 1;
                   7640:             } else {
                   7641:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7642:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7643:                     return 1;
                   7644:                 }
                   7645:             }
                   7646:         }
                   7647:     }
                   7648:     return;
                   7649: }
                   7650: 
1.976     raeburn  7651: sub is_advanced_user {
                   7652:     my ($udom,$uname) = @_;
1.1085    raeburn  7653:     if ($udom ne '' && $uname ne '') {
                   7654:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7655:             if (wantarray) {
                   7656:                 return ($env{'user.adv'},$env{'user.author'});
                   7657:             } else {
                   7658:                 return $env{'user.adv'};
                   7659:             }
1.1085    raeburn  7660:         }
                   7661:     }
1.976     raeburn  7662:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7663:     my %allroles;
1.1128    raeburn  7664:     my ($is_adv,$is_author);
1.976     raeburn  7665:     foreach my $role (keys(%roleshash)) {
                   7666:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7667:         my $area = '/'.$tdomain.'/'.$trest;
                   7668:         if ($sec ne '') {
                   7669:             $area .= '/'.$sec;
                   7670:         }
                   7671:         if (($area ne '') && ($trole ne '')) {
                   7672:             my $spec=$trole.'.'.$area;
                   7673:             if ($trole =~ /^cr\//) {
                   7674:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7675:             } elsif ($trole ne 'gr') {
                   7676:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7677:             }
1.1128    raeburn  7678:             if ($trole eq 'au') {
                   7679:                 $is_author = 1;
                   7680:             }
1.976     raeburn  7681:         }
                   7682:     }
                   7683:     foreach my $role (keys(%allroles)) {
                   7684:         last if ($is_adv);
                   7685:         foreach my $item (split(/:/,$allroles{$role})) {
                   7686:             if ($item ne '') {
                   7687:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7688:                 if ($privilege eq 'adv') {
                   7689:                     $is_adv = 1;
                   7690:                     last;
                   7691:                 }
                   7692:             }
                   7693:         }
                   7694:     }
1.1128    raeburn  7695:     if (wantarray) {
                   7696:         return ($is_adv,$is_author);
                   7697:     }
1.976     raeburn  7698:     return $is_adv;
                   7699: }
1.798     raeburn  7700: 
1.1035    raeburn  7701: sub check_can_request {
1.1036    raeburn  7702:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7703:     my $canreq = 0;
                   7704:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7705:     my @options = ('approval','validate','autolimit');
                   7706:     my $optregex = join('|',@options);
                   7707:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7708:         foreach my $type (@{$types}) {
                   7709:             if (&usertools_access($env{'user.name'},
                   7710:                                   $env{'user.domain'},
                   7711:                                   $type,undef,'requestcourses')) {
                   7712:                 $canreq ++;
1.1036    raeburn  7713:                 if (ref($request_domains) eq 'HASH') {
                   7714:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7715:                 }
1.1035    raeburn  7716:                 if ($dom eq $env{'user.domain'}) {
                   7717:                     $can_request->{$type} = 1;
                   7718:                 }
                   7719:             }
                   7720:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7721:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7722:                 if (@curr > 0) {
1.1036    raeburn  7723:                     foreach my $item (@curr) {
                   7724:                         if (ref($request_domains) eq 'HASH') {
                   7725:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7726:                             if ($otherdom ne '') {
                   7727:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7728:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7729:                                         push(@{$request_domains->{$type}},$otherdom);
                   7730:                                     }
                   7731:                                 } else {
                   7732:                                     push(@{$request_domains->{$type}},$otherdom);
                   7733:                                 }
                   7734:                             }
                   7735:                         }
                   7736:                     }
                   7737:                     unless($dom eq $env{'user.domain'}) {
                   7738:                         $canreq ++;
1.1035    raeburn  7739:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7740:                             $can_request->{$type} = 1;
                   7741:                         }
                   7742:                     }
                   7743:                 }
                   7744:             }
                   7745:         }
                   7746:     }
                   7747:     return $canreq;
                   7748: }
                   7749: 
1.341     www      7750: # ---------------------------------------------- Custom access rule evaluation
                   7751: 
                   7752: sub customaccess {
                   7753:     my ($priv,$uri)=@_;
1.807     albertel 7754:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7755:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7756:     $udom = &LONCAPA::clean_domain($udom);
                   7757:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7758:     my $access=0;
1.800     albertel 7759:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7760: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7761: 	if ($type eq 'user') {
                   7762: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7763: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7764: 		if ($tdom) {
                   7765: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7766: 		}
1.896     albertel 7767: 		if ($tuname) {
                   7768: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7769: 		}
                   7770: 		$access=($effect eq 'allow');
                   7771: 		last;
                   7772: 	    }
                   7773: 	} else {
                   7774: 	    if ($role) {
                   7775: 		if ($role ne $urole) { next; }
                   7776: 	    }
                   7777: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7778: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7779: 		if ($tdom) {
                   7780: 		    if ($tdom ne $udom) { next; }
                   7781: 		}
                   7782: 		if ($tcrs) {
                   7783: 		    if ($tcrs ne $ucrs) { next; }
                   7784: 		}
                   7785: 		if ($tsec) {
                   7786: 		    if ($tsec ne $usec) { next; }
                   7787: 		}
                   7788: 		$access=($effect eq 'allow');
                   7789: 		last;
                   7790: 	    }
                   7791: 	    if ($realm eq '' && $role eq '') {
                   7792: 		$access=($effect eq 'allow');
                   7793: 	    }
1.402     bowersj2 7794: 	}
1.341     www      7795:     }
                   7796:     return $access;
                   7797: }
                   7798: 
1.103     harris41 7799: # ------------------------------------------------- Check for a user privilege
1.12      www      7800: 
                   7801: sub allowed {
1.1172.2.126  raeburn  7802:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7803:     my $ver_orguri=$uri;
1.439     www      7804:     $uri=&deversion($uri);
1.152     www      7805:     my $orguri=$uri;
1.52      www      7806:     $uri=&declutter($uri);
1.809     raeburn  7807: 
1.810     raeburn  7808:     if ($priv eq 'evb') {
                   7809: # Evade communication block restrictions for specified role in a course
                   7810:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7811:             return $1;
                   7812:         } else {
                   7813:             return;
                   7814:         }
                   7815:     }
                   7816: 
1.620     albertel 7817:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7818: # Free bre access to adm and meta resources
1.775     albertel 7819:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7820: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7821: 	&& ($priv eq 'bre')) {
1.14      www      7822: 	return 'F';
1.159     www      7823:     }
                   7824: 
1.545     banghart 7825: # Free bre access to user's own portfolio contents
1.714     raeburn  7826:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7827:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7828: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7829:         my %setters;
                   7830:         my ($startblock,$endblock) = 
                   7831:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7832:         if ($startblock && $endblock) {
                   7833:             return 'B';
                   7834:         } else {
                   7835:             return 'F';
                   7836:         }
1.545     banghart 7837:     }
                   7838: 
1.762     raeburn  7839: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7840:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7841:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7842:         if (exists($env{'request.course.id'})) {
                   7843:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7844:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7845:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7846:                 my $courseprivid=$env{'request.course.id'};
                   7847:                 $courseprivid=~s/\_/\//;
                   7848:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7849:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7850:                     return $1; 
1.762     raeburn  7851:                 } else {
                   7852:                     if ($env{'request.course.sec'}) {
                   7853:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7854:                     }
                   7855:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7856:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7857:                         return $2;
                   7858:                     }
1.714     raeburn  7859:                 }
                   7860:             }
                   7861:         }
                   7862:     }
                   7863: 
1.159     www      7864: # Free bre to public access
                   7865: 
                   7866:     if ($priv eq 'bre') {
1.238     www      7867:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7868: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7869:            return 'F'; 
                   7870:         }
1.238     www      7871:         if ($copyright eq 'priv') {
                   7872:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7873: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7874: 		return '';
                   7875:             }
                   7876:         }
                   7877:         if ($copyright eq 'domain') {
                   7878:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7879: 	    unless (($env{'user.domain'} eq $1) ||
                   7880:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7881: 		return '';
                   7882:             }
1.262     matthew  7883:         }
1.620     albertel 7884:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7885:             # Library role, so allow browsing of resources in this domain.
                   7886:             return 'F';
1.238     www      7887:         }
1.341     www      7888:         if ($copyright eq 'custom') {
                   7889: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7890:         }
1.14      www      7891:     }
1.264     matthew  7892:     # Domain coordinator is trying to create a course
1.620     albertel 7893:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7894:         # uri is the requested domain in this case.
                   7895:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7896:         # a role of dc for the domain in question.
1.620     albertel 7897:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7898:     }
1.29      www      7899: 
1.52      www      7900:     my $thisallowed='';
                   7901:     my $statecond=0;
                   7902:     my $courseprivid='';
                   7903: 
1.1039    raeburn  7904:     my $ownaccess;
1.1043    raeburn  7905:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7906:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7907:         if ($uri eq '') {
                   7908:             $ownaccess = 1;
                   7909:         } else {
                   7910:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7911:                 my $udom = $env{'user.domain'};
                   7912:                 my $uname = $env{'user.name'};
                   7913:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7914:                     $ownaccess = 1;
1.1040    raeburn  7915:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7916:                     unless ($uri =~ m{\.\./}) {
                   7917:                         $ownaccess = 1;
                   7918:                     }
                   7919:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7920:                     my $now = time;
                   7921:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7922:                         my $adom = $1;
                   7923:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7924:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7925:                                 my ($start,$end) = split('.',$env{$key});
                   7926:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7927:                                     $ownaccess = 1;
                   7928:                                     last;
                   7929:                                 }
                   7930:                             }
                   7931:                         }
                   7932:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7933:                         my $adom = $1;
                   7934:                         my $aname = $2;
1.1042    raeburn  7935:                         foreach my $role ('ca','aa') { 
                   7936:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7937:                                 my ($start,$end) =
                   7938:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7939:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7940:                                     $ownaccess = 1;
                   7941:                                     last;
                   7942:                                 }
1.1039    raeburn  7943:                             }
                   7944:                         }
                   7945:                     }
                   7946:                 }
                   7947:             }
                   7948:         }
                   7949:     }
                   7950: 
1.52      www      7951: # Course
                   7952: 
1.620     albertel 7953:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7954:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7955:             $thisallowed.=$1;
                   7956:         }
1.52      www      7957:     }
1.29      www      7958: 
1.52      www      7959: # Domain
                   7960: 
1.620     albertel 7961:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7962:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7963:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7964:             $thisallowed.=$1;
                   7965:         }
1.12      www      7966:     }
1.52      www      7967: 
1.1141    raeburn  7968: # User who is not author or co-author might still be able to edit
                   7969: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7970:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7971:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7972:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7973:             $thisallowed.=$1;
                   7974:         }
                   7975:     }
                   7976: 
1.52      www      7977: # Course: uri itself is a course
1.66      www      7978:     my $courseuri=$uri;
                   7979:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7980:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7981: 
1.620     albertel 7982:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7983:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7984:         if ($priv eq 'mip') {
                   7985:             my $rem = $1;
                   7986:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7987:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7988:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7989:                 if ($cdom ne '') {
                   7990:                     my %passwdconf = &get_passwdconf($cdom);
                   7991:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7992:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7993:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7994:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7995:                                 unless (@inststatuses) {
                   7996:                                     @inststatuses = ('default');
                   7997:                                 }
                   7998:                                 foreach my $status (@inststatuses) {
                   7999:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8000:                                         $thisallowed.=$rem;
                   8001:                                     }
                   8002:                                 }
                   8003:                             }
                   8004:                         }
                   8005:                     }
                   8006:                 }
                   8007:             }
                   8008:         } else {
                   8009:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8010:                 $thisallowed.=$1;
                   8011:             }
1.1039    raeburn  8012:         }
1.12      www      8013:     }
1.29      www      8014: 
1.665     albertel 8015: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8016: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8017:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8018: 	$thisallowed='';
1.671     raeburn  8019:         my ($match)=&is_on_map($uri);
                   8020:         if ($match) {
                   8021:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8022:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8023:                 my $value = $1;
                   8024:                 if ($noblockcheck) {
                   8025:                     $thisallowed.=$value;
1.1162    raeburn  8026:                 } else {
1.1172.2.126  raeburn  8027:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8028:                     if (@blockers > 0) {
                   8029:                         $thisallowed = 'B';
                   8030:                     } else {
                   8031:                         $thisallowed.=$value;
                   8032:                     }
1.1162    raeburn  8033:                 }
1.671     raeburn  8034:             }
                   8035:         } else {
1.705     albertel 8036:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8037:             if ($refuri) {
                   8038:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8039:                     $thisallowed='F';
1.671     raeburn  8040:                 } else {
                   8041:                     $refuri=&declutter($refuri);
                   8042:                     my ($match) = &is_on_map($refuri);
                   8043:                     if ($match) {
1.1172.2.65  raeburn  8044:                         if ($noblockcheck) {
1.1162    raeburn  8045:                             $thisallowed='F';
1.1172.2.65  raeburn  8046:                         } else {
1.1172.2.127  raeburn  8047:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8048:                             if (@blockers > 0) {
                   8049:                                 $thisallowed = 'B';
                   8050:                             } else {
                   8051:                                 $thisallowed='F';
                   8052:                             }
1.1162    raeburn  8053:                         }
1.671     raeburn  8054:                     }
1.669     raeburn  8055:                 }
1.671     raeburn  8056:             }
                   8057:         }
1.314     www      8058:     }
1.492     albertel 8059: 
1.766     albertel 8060:     if ($priv eq 'bre'
                   8061: 	&& $thisallowed ne 'F' 
                   8062: 	&& $thisallowed ne '2'
                   8063: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8064: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8065:     }
                   8066:     
1.52      www      8067: # Full access at system, domain or course-wide level? Exit.
1.29      www      8068:     if ($thisallowed=~/F/) {
                   8069: 	return 'F';
                   8070:     }
                   8071: 
1.52      www      8072: # If this is generating or modifying users, exit with special codes
1.29      www      8073: 
1.643     www      8074:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8075: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8076: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8077: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8078: 	    unless ($auname) { return $thisallowed; }
                   8079: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8080: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8081: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8082: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8083: 	}
1.52      www      8084: 	return $thisallowed;
                   8085:     }
                   8086: #
1.103     harris41 8087: # Gathered so far: system, domain and course wide privileges
1.52      www      8088: #
                   8089: # Course: See if uri or referer is an individual resource that is part of 
                   8090: # the course
                   8091: 
1.620     albertel 8092:     if ($env{'request.course.id'}) {
1.232     www      8093: 
1.1172.2.115  raeburn  8094: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8095: 
                   8096:         if ($priv eq 'mip') {
                   8097:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8098:                 return $thisallowed;
                   8099:             } else {
                   8100:                 return '';
                   8101:             }
                   8102:         }
                   8103: 
1.620     albertel 8104:        $courseprivid=$env{'request.course.id'};
                   8105:        if ($env{'request.course.sec'}) {
                   8106:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8107:        }
                   8108:        $courseprivid=~s/\_/\//;
                   8109:        my $checkreferer=1;
1.232     www      8110:        my ($match,$cond)=&is_on_map($uri);
                   8111:        if ($match) {
                   8112:            $statecond=$cond;
1.620     albertel 8113:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8114:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8115:                my $value = $1;
                   8116:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8117:                    if ($noblockcheck) {
1.1162    raeburn  8118:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8119:                    } else {
1.1172.2.126  raeburn  8120:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8121:                        if (@blockers > 0) {
                   8122:                            $thisallowed = 'B';
                   8123:                        } else {
                   8124:                            $thisallowed.=$value;
                   8125:                        }
1.1162    raeburn  8126:                    }
                   8127:                } else {
                   8128:                    $thisallowed.=$value;
                   8129:                }
1.52      www      8130:                $checkreferer=0;
                   8131:            }
1.29      www      8132:        }
1.1172.2.126  raeburn  8133: 
1.148     www      8134:        if ($checkreferer) {
1.620     albertel 8135: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8136:             unless ($refuri) {
1.800     albertel 8137:                 foreach my $key (keys(%env)) {
                   8138: 		    if ($key=~/^httpref\..*\*/) {
                   8139: 			my $pattern=$key;
1.156     www      8140:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8141:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8142:                         $pattern=~s/\//\\\//g;
1.152     www      8143:                         if ($orguri=~/$pattern/) {
1.800     albertel 8144: 			    $refuri=$env{$key};
1.148     www      8145:                         }
                   8146:                     }
1.191     harris41 8147:                 }
1.148     www      8148:             }
1.232     www      8149: 
1.148     www      8150:          if ($refuri) { 
1.152     www      8151: 	  $refuri=&declutter($refuri);
1.232     www      8152:           my ($match,$cond)=&is_on_map($refuri);
                   8153:             if ($match) {
                   8154:               my $refstatecond=$cond;
1.620     albertel 8155:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8156:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8157:                   my $value = $1;
                   8158:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8159:                       if ($noblockcheck) {
1.1162    raeburn  8160:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8161:                       } else {
1.1172.2.127  raeburn  8162:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8163:                           if (@blockers > 0) {
                   8164:                               $thisallowed = 'B';
                   8165:                           } else {
                   8166:                               $thisallowed.=$value;
                   8167:                           }
1.1162    raeburn  8168:                       }
                   8169:                   } else {
                   8170:                       $thisallowed.=$value;
                   8171:                   }
1.53      www      8172:                   $uri=$refuri;
                   8173:                   $statecond=$refstatecond;
1.52      www      8174:               }
                   8175:           }
1.148     www      8176:         }
1.29      www      8177:        }
1.52      www      8178:    }
1.29      www      8179: 
1.52      www      8180: #
1.103     harris41 8181: # Gathered now: all privileges that could apply, and condition number
1.52      www      8182: # 
                   8183: #
                   8184: # Full or no access?
                   8185: #
1.29      www      8186: 
1.52      www      8187:     if ($thisallowed=~/F/) {
                   8188: 	return 'F';
                   8189:     }
1.29      www      8190: 
1.52      www      8191:     unless ($thisallowed) {
                   8192:         return '';
                   8193:     }
1.29      www      8194: 
1.52      www      8195: # Restrictions exist, deal with them
                   8196: #
                   8197: #   C:according to course preferences
                   8198: #   R:according to resource settings
                   8199: #   L:unless locked
                   8200: #   X:according to user session state
                   8201: #
                   8202: 
                   8203: # Possibly locked functionality, check all courses
1.54      www      8204: # Locks might take effect only after 10 minutes cache expiration for other
                   8205: # courses, and 2 minutes for current course
1.52      www      8206: 
                   8207:     my $envkey;
                   8208:     if ($thisallowed=~/L/) {
1.1000    raeburn  8209:         foreach $envkey (keys(%env)) {
1.54      www      8210:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8211:                my $courseid=$2;
                   8212:                my $roleid=$1.'.'.$2;
1.92      www      8213:                $courseid=~s/^\///;
1.54      www      8214:                my $expiretime=600;
1.620     albertel 8215:                if ($env{'request.role'} eq $roleid) {
1.54      www      8216: 		  $expiretime=120;
                   8217:                }
                   8218: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8219:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8220:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8221: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8222:                }
1.620     albertel 8223:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8224:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8225: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8226:                        &log($env{'user.domain'},$env{'user.name'},
                   8227:                             $env{'user.home'},
1.57      www      8228:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8229:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8230:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8231: 		       return '';
                   8232:                    }
                   8233:                }
1.620     albertel 8234:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8235:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8236: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8237:                        &log($env{'user.domain'},$env{'user.name'},
                   8238:                             $env{'user.home'},
1.57      www      8239:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8240:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8241:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8242: 		       return '';
                   8243:                    }
                   8244:                }
                   8245: 	   }
1.29      www      8246:        }
1.52      www      8247:     }
1.1172.2.126  raeburn  8248: 
1.52      www      8249: #
                   8250: # Rest of the restrictions depend on selected course
                   8251: #
                   8252: 
1.620     albertel 8253:     unless ($env{'request.course.id'}) {
1.766     albertel 8254: 	if ($thisallowed eq 'A') {
                   8255: 	    return 'A';
1.814     raeburn  8256:         } elsif ($thisallowed eq 'B') {
                   8257:             return 'B';
1.766     albertel 8258: 	} else {
                   8259: 	    return '1';
                   8260: 	}
1.52      www      8261:     }
1.29      www      8262: 
1.52      www      8263: #
                   8264: # Now user is definitely in a course
                   8265: #
1.53      www      8266: 
                   8267: 
                   8268: # Course preferences
                   8269: 
                   8270:    if ($thisallowed=~/C/) {
1.620     albertel 8271:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8272:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8273:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8274: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8275: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8276: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8277: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8278: 			$env{'request.course.id'});
                   8279: 	   }
1.237     www      8280:            return '';
                   8281:        }
                   8282: 
1.620     albertel 8283:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8284: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8285: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8286: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8287: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8288: 			$env{'request.course.id'});
                   8289: 	   }
1.54      www      8290:            return '';
                   8291:        }
1.53      www      8292:    }
                   8293: 
                   8294: # Resource preferences
                   8295: 
                   8296:    if ($thisallowed=~/R/) {
1.620     albertel 8297:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8298:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8299: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8300: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8301: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8302: 	   }
                   8303: 	   return '';
1.54      www      8304:        }
1.53      www      8305:    }
1.30      www      8306: 
1.246     www      8307: # Restricted by state or randomout?
1.30      www      8308: 
1.52      www      8309:    if ($thisallowed=~/X/) {
1.620     albertel 8310:       if ($env{'acc.randomout'}) {
1.579     albertel 8311: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8312:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8313:             return ''; 
                   8314:          }
1.247     www      8315:       }
                   8316:       if (&condval($statecond)) {
1.52      www      8317: 	 return '2';
                   8318:       } else {
                   8319:          return '';
                   8320:       }
                   8321:    }
1.30      www      8322: 
1.766     albertel 8323:     if ($thisallowed eq 'A') {
                   8324: 	return 'A';
1.814     raeburn  8325:     } elsif ($thisallowed eq 'B') {
                   8326:         return 'B';
1.766     albertel 8327:     }
1.52      www      8328:    return 'F';
1.232     www      8329: }
1.1162    raeburn  8330: 
1.1172.2.13  raeburn  8331: # ------------------------------------------- Check construction space access
                   8332: 
                   8333: sub constructaccess {
                   8334:     my ($url,$setpriv)=@_;
                   8335: 
                   8336: # We do not allow editing of previous versions of files
                   8337:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8338: 
                   8339: # Get username and domain from URL
                   8340:     my ($ownername,$ownerdomain,$ownerhome);
                   8341: 
                   8342:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8343:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8344: 
                   8345: # The URL does not really point to any authorspace, forget it
                   8346:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8347: 
                   8348: # Now we need to see if the user has access to the authorspace of
                   8349: # $ownername at $ownerdomain
                   8350: 
                   8351:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8352: # Real author for this?
                   8353:        $ownerhome = $env{'user.home'};
                   8354:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8355:           return ($ownername,$ownerdomain,$ownerhome);
                   8356:        }
                   8357:     } else {
                   8358: # Co-author for this?
                   8359:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8360:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8361:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8362:             return ($ownername,$ownerdomain,$ownerhome);
                   8363:         }
                   8364:     }
                   8365: 
                   8366: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8367: # we might as well leave
                   8368:    unless ($setpriv) { return ''; }
                   8369: 
                   8370: # Backdoor access?
                   8371:     my $allowed=&allowed('eco',$ownerdomain);
                   8372: # Nope
                   8373:     unless ($allowed) { return ''; }
                   8374: # Looks like we may have access, but could be locked by the owner of the construction space
                   8375:     if ($allowed eq 'U') {
                   8376:         my %blocked=&get('environment',['domcoord.author'],
                   8377:                          $ownerdomain,$ownername);
                   8378: # Is blocked by owner
                   8379:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8380:     }
                   8381:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8382: # Grant temporary access
                   8383:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8384:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8385:         if (!$update) { $update = $then; }
                   8386:         my $refresh=$env{'user.refresh.time'};
                   8387:         if (!$refresh) { $refresh = $update; }
                   8388:         my $now = time;
                   8389:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8390:                            $now,'ca','constructaccess');
                   8391:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8392:         return($ownername,$ownerdomain,$ownerhome);
                   8393:     }
                   8394: # No business here
                   8395:     return '';
                   8396: }
                   8397: 
1.1172.2.66  raeburn  8398: # ----------------------------------------------------------- Content Blocking
                   8399: 
                   8400: {
                   8401: # Caches for faster Course Contents display where content blocking
                   8402: # is in operation (i.e., interval param set) for timed quiz.
                   8403: #
                   8404: # User for whom data are being temporarily cached.
                   8405: my $cacheduser='';
1.1172.2.126  raeburn  8406: # Course for which data are being temporarily cached.
                   8407: my $cachedcid='';
1.1172.2.66  raeburn  8408: # Cached blockers for this user (a hash of blocking items).
                   8409: my %cachedblockers=();
                   8410: # When the data were last cached.
                   8411: my $cachedlast='';
                   8412: 
                   8413: sub load_all_blockers {
1.1172.2.128  raeburn  8414:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8415:     if (($uname ne '') && ($udom ne '')) {
                   8416:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8417:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8418:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8419:             return;
                   8420:         }
                   8421:     }
                   8422:     $cachedlast=time;
                   8423:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8424:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8425:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8426:     return;
1.1172.2.66  raeburn  8427: }
                   8428: 
1.1162    raeburn  8429: sub get_comm_blocks {
                   8430:     my ($cdom,$cnum) = @_;
                   8431:     if ($cdom eq '' || $cnum eq '') {
                   8432:         return unless ($env{'request.course.id'});
                   8433:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8434:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8435:     }
                   8436:     my %commblocks;
                   8437:     my $hashid=$cdom.'_'.$cnum;
                   8438:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8439:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8440:         %commblocks = %{$blocksref};
                   8441:     } else {
                   8442:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8443:         my $cachetime = 600;
                   8444:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8445:     }
                   8446:     return %commblocks;
                   8447: }
                   8448: 
1.1172.2.66  raeburn  8449: sub get_commblock_resources {
                   8450:     my ($blocks) = @_;
                   8451:     my %blockers = ();
                   8452:     return %blockers unless ($env{'request.course.id'});
                   8453:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8454:     my %commblocks;
                   8455:     if (ref($blocks) eq 'HASH') {
                   8456:         %commblocks = %{$blocks};
                   8457:     } else {
                   8458:         %commblocks = &get_comm_blocks();
                   8459:     }
1.1172.2.66  raeburn  8460:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8461:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8462:     return %blockers unless (ref($navmap));
                   8463:     my $now = time;
1.1162    raeburn  8464:     foreach my $block (keys(%commblocks)) {
                   8465:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8466:             my ($start,$end) = ($1,$2);
                   8467:             if ($start <= $now && $end >= $now) {
                   8468:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8469:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8470:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8471:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8472:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8473:                             }
                   8474:                         }
                   8475:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8476:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8477:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8478:                             }
                   8479:                         }
                   8480:                     }
                   8481:                 }
                   8482:             }
                   8483:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8484:             my $item = $1;
1.1163    raeburn  8485:             my @to_test;
1.1162    raeburn  8486:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8487:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8488:                     my @interval;
                   8489:                     my $type = 'map';
                   8490:                     if ($item eq 'course') {
                   8491:                         $type = 'course';
                   8492:                         @interval=&EXT("resource.0.interval");
                   8493:                     } else {
                   8494:                         if ($item =~ /___\d+___/) {
                   8495:                             $type = 'resource';
                   8496:                             @interval=&EXT("resource.0.interval",$item);
                   8497:                             if (ref($navmap)) {
                   8498:                                 my $res = $navmap->getBySymb($item);
                   8499:                                 push(@to_test,$res);
                   8500:                             }
1.1162    raeburn  8501:                         } else {
1.1172.2.66  raeburn  8502:                             my $mapsymb = &symbread($item,1);
                   8503:                             if ($mapsymb) {
                   8504:                                 if (ref($navmap)) {
                   8505:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129  raeburn  8506:                                     if (ref($mapres)) {
                   8507:                                         my $first = $mapres->map_start();
                   8508:                                         my $finish = $mapres->map_finish();
                   8509:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8510:                                         if (ref($it)) {
                   8511:                                             my $res;
                   8512:                                             while ($res = $it->next(undef,1)) {
                   8513:                                                 next unless (ref($res));
                   8514:                                                 my $symb = $res->symb();
                   8515:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8516:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8517:                                                 if ($interval[1] eq 'map') {
                   8518:                                                     if ($res->answerable()) {
                   8519:                                                         push(@to_test,$res);
                   8520:                                                         last;
                   8521:                                                     }
                   8522:                                                 }
1.1162    raeburn  8523:                                             }
                   8524:                                         }
                   8525:                                     }
                   8526:                                 }
                   8527:                             }
                   8528:                         }
1.1172.2.66  raeburn  8529:                     }
                   8530:                     if ($interval[0] =~ /^\d+$/) {
                   8531:                         my $first_access;
                   8532:                         if ($type eq 'resource') {
                   8533:                             $first_access=&get_first_access($interval[1],$item);
                   8534:                         } elsif ($type eq 'map') {
                   8535:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8536:                         } else {
                   8537:                             $first_access=&get_first_access($interval[1]);
                   8538:                         }
                   8539:                         if ($first_access) {
                   8540:                             my $timesup = $first_access+$interval[0];
                   8541:                             if ($timesup > $now) {
                   8542:                                 my $activeblock;
                   8543:                                 foreach my $res (@to_test) {
                   8544:                                     if ($res->answerable()) {
                   8545:                                         $activeblock = 1;
                   8546:                                         last;
                   8547:                                     }
                   8548:                                 }
                   8549:                                 if ($activeblock) {
                   8550:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8551:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8552:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8553:                                          }
                   8554:                                     }
                   8555:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8556:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8557:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8558:                                         }
1.1162    raeburn  8559:                                     }
                   8560:                                 }
                   8561:                             }
                   8562:                         }
                   8563:                     }
                   8564:                 }
                   8565:             }
                   8566:         }
                   8567:     }
1.1172.2.66  raeburn  8568:     return %blockers;
1.1162    raeburn  8569: }
                   8570: 
1.1172.2.66  raeburn  8571: sub has_comm_blocking {
1.1172.2.128  raeburn  8572:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8573:     my @blockers;
                   8574:     return unless ($env{'request.course.id'});
                   8575:     return unless ($priv eq 'bre');
                   8576:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8577:     return if ($env{'request.state'} eq 'construct');
1.1172.2.128  raeburn  8578:     my %blockinfo;
                   8579:     if (ref($blocks) eq 'HASH') {
                   8580:         %blockinfo = &get_commblock_resources($blocks);
                   8581:     } else {
                   8582:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8583:         %blockinfo = %cachedblockers;
                   8584:     }
                   8585:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8586:     my (%possibles,@symbs);
                   8587:     if (!$symb) {
1.1172.2.128  raeburn  8588:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8589:     }
1.1172.2.66  raeburn  8590:     if ($symb) {
                   8591:         @symbs = ($symb);
                   8592:     } elsif (keys(%possibles)) {
                   8593:         @symbs = keys(%possibles);
                   8594:     }
                   8595:     my $noblock;
                   8596:     foreach my $symb (@symbs) {
                   8597:         last if ($noblock);
                   8598:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8599:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8600:             if ($block =~ /^firstaccess____(.+)$/) {
                   8601:                 my $item = $1;
1.1172.2.126  raeburn  8602:                 unless ($blocked) {
                   8603:                     if (($item eq $map) || ($item eq $symb)) {
                   8604:                         $noblock = 1;
                   8605:                         last;
                   8606:                     }
1.1172.2.66  raeburn  8607:                 }
1.1162    raeburn  8608:             }
1.1172.2.128  raeburn  8609:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8610:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8611:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8612:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8613:                             push(@blockers,$block);
                   8614:                         }
                   8615:                     }
                   8616:                 }
1.1172.2.128  raeburn  8617:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8618:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8619:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8620:                             push(@blockers,$block);
                   8621:                         }
1.1172.2.66  raeburn  8622:                     }
                   8623:                 }
1.1162    raeburn  8624:             }
                   8625:         }
                   8626:     }
1.1172.2.126  raeburn  8627:     unless ($noblock) {
                   8628:         return @blockers;
                   8629:     }
                   8630:     return;
1.1172.2.66  raeburn  8631: }
1.1162    raeburn  8632: }
                   8633: 
1.1172.2.66  raeburn  8634: # -------------------------------- Deversion and split uri into path an filename
                   8635: 
1.1133    foxr     8636: #
1.1172.2.66  raeburn  8637: #   Removes the version from a URI and
1.1133    foxr     8638: #   splits it in to its filename and path to the filename.
                   8639: #   Seems like File::Basename could have done this more clearly.
                   8640: #   Parameters:
                   8641: #      $uri   - input URI
                   8642: #   Returns:
                   8643: #     Two element list consisting of 
                   8644: #     $pathname  - the URI up to and excluding the trailing /
                   8645: #     $filename  - The part of the URI following the last /
                   8646: #  NOTE:
                   8647: #    Another realization of this is simply:
                   8648: #    use File::Basename;
                   8649: #    ...
                   8650: #    $uri = shift;
                   8651: #    $filename = basename($uri);
                   8652: #    $path     = dirname($uri);
                   8653: #    return ($filename, $path);
                   8654: #
                   8655: #     The implementation below is probably faster however.
                   8656: #
1.710     albertel 8657: sub split_uri_for_cond {
                   8658:     my $uri=&deversion(&declutter(shift));
                   8659:     my @uriparts=split(/\//,$uri);
                   8660:     my $filename=pop(@uriparts);
                   8661:     my $pathname=join('/',@uriparts);
                   8662:     return ($pathname,$filename);
                   8663: }
1.232     www      8664: # --------------------------------------------------- Is a resource on the map?
                   8665: 
                   8666: sub is_on_map {
1.710     albertel 8667:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8668:     #Trying to find the conditional for the file
1.620     albertel 8669:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8670: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8671:     if ($match) {
1.289     bowersj2 8672: 	return (1,$1);
                   8673:     } else {
1.434     www      8674: 	return (0,0);
1.289     bowersj2 8675:     }
1.12      www      8676: }
                   8677: 
1.427     www      8678: # --------------------------------------------------------- Get symb from alias
                   8679: 
                   8680: sub get_symb_from_alias {
                   8681:     my $symb=shift;
                   8682:     my ($map,$resid,$url)=&decode_symb($symb);
                   8683: # Already is a symb
                   8684:     if ($url) { return $symb; }
                   8685: # Must be an alias
                   8686:     my $aliassymb='';
                   8687:     my %bighash;
1.620     albertel 8688:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8689:                             &GDBM_READER(),0640)) {
                   8690:         my $rid=$bighash{'mapalias_'.$symb};
                   8691: 	if ($rid) {
                   8692: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8693: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8694: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8695: 	}
                   8696:         untie %bighash;
                   8697:     }
                   8698:     return $aliassymb;
                   8699: }
                   8700: 
1.12      www      8701: # ----------------------------------------------------------------- Define Role
                   8702: 
                   8703: sub definerole {
                   8704:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8705:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8706:     foreach my $role (split(':',$sysrole)) {
                   8707: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8708:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8709:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8710: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8711:                return "refused:s:$crole&$cqual"; 
                   8712:             }
                   8713:         }
1.191     harris41 8714:     }
1.800     albertel 8715:     foreach my $role (split(':',$domrole)) {
                   8716: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8717:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8718:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8719: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8720:                return "refused:d:$crole&$cqual"; 
                   8721:             }
                   8722:         }
1.191     harris41 8723:     }
1.800     albertel 8724:     foreach my $role (split(':',$courole)) {
                   8725: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8726:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8727:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8728: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8729:                return "refused:c:$crole&$cqual"; 
                   8730:             }
                   8731:         }
1.191     harris41 8732:     }
1.1172.2.84  raeburn  8733:     my $uhome;
                   8734:     if (($uname ne '') && ($udom ne '')) {
                   8735:         $uhome = &homeserver($uname,$udom);
                   8736:         return $uhome if ($uhome eq 'no_host');
                   8737:     } else {
                   8738:         $uname = $env{'user.name'};
                   8739:         $udom = $env{'user.domain'};
                   8740:         $uhome = $env{'user.home'};
                   8741:     }
1.620     albertel 8742:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8743:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8744:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8745:     return reply($command,$uhome);
1.12      www      8746:   } else {
                   8747:     return 'refused';
                   8748:   }
1.105     harris41 8749: }
                   8750: 
                   8751: # ---------------- Make a metadata query against the network of library servers
                   8752: 
                   8753: sub metadata_query {
1.1172.2.33  raeburn  8754:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8755:     my %rhash;
1.845     albertel 8756:     my %libserv = &all_library();
1.244     matthew  8757:     my @server_list = (defined($server_array) ? @$server_array
                   8758:                                               : keys(%libserv) );
                   8759:     for my $server (@server_list) {
1.1172.2.33  raeburn  8760:         my $domains = '';
                   8761:         if (ref($domains_hash) eq 'HASH') {
                   8762:             $domains = $domains_hash->{$server};    
                   8763:         }
1.118     harris41 8764: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8765: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8766: 	    $rhash{$server}=$reply;
                   8767: 	}
                   8768: 	else {
                   8769: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8770: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8771: 			     $server);
                   8772: 	    $rhash{$server}=$reply;
                   8773: 	}
1.112     harris41 8774:     }
1.118     harris41 8775:     return \%rhash;
1.240     www      8776: }
                   8777: 
                   8778: # ----------------------------------------- Send log queries and wait for reply
                   8779: 
                   8780: sub log_query {
                   8781:     my ($uname,$udom,$query,%filters)=@_;
                   8782:     my $uhome=&homeserver($uname,$udom);
                   8783:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8784:     my $uhost=&hostname($uhome);
1.800     albertel 8785:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8786:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8787:                        $uhome);
1.479     albertel 8788:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8789:     return get_query_reply($queryid);
                   8790: }
                   8791: 
1.818     raeburn  8792: # -------------------------- Update MySQL table for portfolio file
                   8793: 
                   8794: sub update_portfolio_table {
1.821     raeburn  8795:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8796:     if ($group ne '') {
                   8797:         $file_name =~s /^\Q$group\E//;
                   8798:     }
1.818     raeburn  8799:     my $homeserver = &homeserver($uname,$udom);
                   8800:     my $queryid=
1.821     raeburn  8801:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8802:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8803:     my $reply = &get_query_reply($queryid);
                   8804:     return $reply;
                   8805: }
                   8806: 
1.899     raeburn  8807: # -------------------------- Update MySQL allusers table
                   8808: 
                   8809: sub update_allusers_table {
                   8810:     my ($uname,$udom,$names) = @_;
                   8811:     my $homeserver = &homeserver($uname,$udom);
                   8812:     my $queryid=
                   8813:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8814:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8815:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8816:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8817:                'generation='.&escape($names->{'generation'}).'%%'.
                   8818:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8819:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8820:     return;
1.899     raeburn  8821: }
                   8822: 
1.508     raeburn  8823: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8824: 
                   8825: sub fetch_enrollment_query {
1.511     raeburn  8826:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8827:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8828:     my $maxtries = 1;
1.508     raeburn  8829:     if ($context eq 'automated') {
                   8830:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8831:         $sleep = 2;
                   8832:         $loopmax = 100;
1.547     raeburn  8833:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8834:     } else {
                   8835:         $homeserver = &homeserver($cnum,$dom);
                   8836:     }
1.838     albertel 8837:     my $host=&hostname($homeserver);
1.506     raeburn  8838:     my $cmd = '';
1.1000    raeburn  8839:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8840:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8841:     }
                   8842:     $cmd =~ s/%%$//;
                   8843:     $cmd = &escape($cmd);
                   8844:     my $query = 'fetchenrollment';
1.620     albertel 8845:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8846:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8847:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8848:         return 'error: '.$queryid;
                   8849:     }
1.1172.2.93  raeburn  8850:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8851:     my $tries = 1;
                   8852:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8853:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8854:         $tries ++;
                   8855:     }
1.526     raeburn  8856:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8857:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8858:     } else {
1.901     albertel 8859:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8860:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8861:             foreach my $line (@responses) {
                   8862:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8863:                 $$replyref{$key} = $value;
                   8864:             }
                   8865:         } else {
1.1117    foxr     8866:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8867:             foreach my $line (@responses) {
                   8868:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8869:                 $$replyref{$key} = $value;
                   8870:                 if ($value > 0) {
1.800     albertel 8871:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8872:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8873:                         my $destname = $pathname.'/'.$filename;
                   8874:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8875:                         if ($xml_classlist =~ /^error/) {
                   8876:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8877:                         } else {
1.1172.2.96  raeburn  8878:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8879:                                 print FILE &unescape($xml_classlist);
                   8880:                                 close(FILE);
1.526     raeburn  8881:                             } else {
                   8882:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8883:                             }
                   8884:                         }
                   8885:                     }
                   8886:                 }
                   8887:             }
                   8888:         }
                   8889:         return 'ok';
                   8890:     }
                   8891:     return 'error';
                   8892: }
                   8893: 
1.242     www      8894: sub get_query_reply {
1.1172.2.79  raeburn  8895:     my ($queryid,$sleep,$loopmax) = @_;
                   8896:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8897:         $sleep = 0.2;
                   8898:     }
                   8899:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8900:         $loopmax = 100;
                   8901:     }
1.1117    foxr     8902:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8903:     my $reply='';
1.1172.2.79  raeburn  8904:     for (1..$loopmax) {
                   8905: 	sleep($sleep);
1.240     www      8906:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8907: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8908: 		$reply = join('',<$fh>);
                   8909: 		close($fh);
1.240     www      8910: 	   } else { return 'error: reply_file_error'; }
1.242     www      8911:            return &unescape($reply);
                   8912: 	}
1.240     www      8913:     }
1.242     www      8914:     return 'timeout:'.$queryid;
1.240     www      8915: }
                   8916: 
                   8917: sub courselog_query {
1.241     www      8918: #
                   8919: # possible filters:
                   8920: # url: url or symb
                   8921: # username
                   8922: # domain
                   8923: # action: view, submit, grade
                   8924: # start: timestamp
                   8925: # end: timestamp
                   8926: #
1.240     www      8927:     my (%filters)=@_;
1.620     albertel 8928:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8929:     if ($filters{'url'}) {
                   8930: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8931:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8932:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8933:     }
1.620     albertel 8934:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8935:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8936:     return &log_query($cname,$cdom,'courselog',%filters);
                   8937: }
                   8938: 
                   8939: sub userlog_query {
1.858     raeburn  8940: #
                   8941: # possible filters:
                   8942: # action: log check role
                   8943: # start: timestamp
                   8944: # end: timestamp
                   8945: #
1.240     www      8946:     my ($uname,$udom,%filters)=@_;
                   8947:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8948: }
                   8949: 
1.506     raeburn  8950: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8951: 
                   8952: sub auto_run {
1.508     raeburn  8953:     my ($cnum,$cdom) = @_;
1.876     raeburn  8954:     my $response = 0;
                   8955:     my $settings;
                   8956:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8957:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8958:         $settings = $domconfig{'autoenroll'};
                   8959:         if ($settings->{'run'} eq '1') {
                   8960:             $response = 1;
                   8961:         }
                   8962:     } else {
1.934     raeburn  8963:         my $homeserver;
                   8964:         if (&is_course($cdom,$cnum)) {
                   8965:             $homeserver = &homeserver($cnum,$cdom);
                   8966:         } else {
                   8967:             $homeserver = &domain($cdom,'primary');
                   8968:         }
                   8969:         if ($homeserver ne 'no_host') {
                   8970:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8971:         }
1.876     raeburn  8972:     }
1.506     raeburn  8973:     return $response;
                   8974: }
1.776     albertel 8975: 
1.506     raeburn  8976: sub auto_get_sections {
1.508     raeburn  8977:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8978:     my $homeserver;
                   8979:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8980:         $homeserver = &homeserver($cnum,$cdom);
                   8981:     }
                   8982:     if (!defined($homeserver)) { 
                   8983:         if ($cdom =~ /^$match_domain$/) {
                   8984:             $homeserver = &domain($cdom,'primary');
                   8985:         }
                   8986:     }
                   8987:     my @secs;
                   8988:     if (defined($homeserver)) {
                   8989:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8990:         unless ($response eq 'refused') {
                   8991:             @secs = split(/:/,$response);
                   8992:         }
1.506     raeburn  8993:     }
                   8994:     return @secs;
                   8995: }
1.776     albertel 8996: 
1.506     raeburn  8997: sub auto_new_course {
1.1099    raeburn  8998:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8999:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9000:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9001:     return $response;
                   9002: }
1.776     albertel 9003: 
1.506     raeburn  9004: sub auto_validate_courseID {
1.508     raeburn  9005:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9006:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9007:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9008:     return $response;
                   9009: }
1.776     albertel 9010: 
1.1007    raeburn  9011: sub auto_validate_instcode {
1.1020    raeburn  9012:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9013:     my ($homeserver,$response);
                   9014:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9015:         $homeserver = &homeserver($cnum,$cdom);
                   9016:     }
                   9017:     if (!defined($homeserver)) {
                   9018:         if ($cdom =~ /^$match_domain$/) {
                   9019:             $homeserver = &domain($cdom,'primary');
                   9020:         }
                   9021:     }
1.1065    raeburn  9022:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9023:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9024:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9025:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9026: }
                   9027: 
1.506     raeburn  9028: sub auto_create_password {
1.873     raeburn  9029:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9030:     my ($homeserver,$response);
1.506     raeburn  9031:     my $create_passwd = 0;
                   9032:     my $authchk = '';
1.873     raeburn  9033:     if ($udom =~ /^$match_domain$/) {
                   9034:         $homeserver = &domain($udom,'primary');
                   9035:     }
                   9036:     if ($homeserver eq '') {
                   9037:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9038:             $homeserver = &homeserver($cnum,$cdom);
                   9039:         }
                   9040:     }
                   9041:     if ($homeserver eq '') {
                   9042:         $authchk = 'nodomain';
1.506     raeburn  9043:     } else {
1.873     raeburn  9044:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9045:         if ($response eq 'refused') {
                   9046:             $authchk = 'refused';
                   9047:         } else {
1.901     albertel 9048:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9049:         }
1.506     raeburn  9050:     }
                   9051:     return ($authparam,$create_passwd,$authchk);
                   9052: }
                   9053: 
1.706     raeburn  9054: sub auto_photo_permission {
                   9055:     my ($cnum,$cdom,$students) = @_;
                   9056:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9057:     my ($outcome,$perm_reqd,$conditions) = 
                   9058: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9059:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9060: 	return (undef,undef);
                   9061:     }
1.706     raeburn  9062:     return ($outcome,$perm_reqd,$conditions);
                   9063: }
                   9064: 
                   9065: sub auto_checkphotos {
                   9066:     my ($uname,$udom,$pid) = @_;
                   9067:     my $homeserver = &homeserver($uname,$udom);
                   9068:     my ($result,$resulttype);
                   9069:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9070: 				   &escape($uname).':'.&escape($pid),
                   9071: 				   $homeserver));
1.709     albertel 9072:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9073: 	return (undef,undef);
                   9074:     }
1.706     raeburn  9075:     if ($outcome) {
                   9076:         ($result,$resulttype) = split(/:/,$outcome);
                   9077:     } 
                   9078:     return ($result,$resulttype);
                   9079: }
                   9080: 
                   9081: sub auto_photochoice {
                   9082:     my ($cnum,$cdom) = @_;
                   9083:     my $homeserver = &homeserver($cnum,$cdom);
                   9084:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9085: 						       &escape($cdom),
                   9086: 						       $homeserver)));
1.709     albertel 9087:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9088: 	return (undef,undef);
                   9089:     }
1.706     raeburn  9090:     return ($update,$comment);
                   9091: }
                   9092: 
                   9093: sub auto_photoupdate {
                   9094:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9095:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9096:     my $host=&hostname($homeserver);
1.706     raeburn  9097:     my $cmd = '';
                   9098:     my $maxtries = 1;
1.800     albertel 9099:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9100:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9101:     }
                   9102:     $cmd =~ s/%%$//;
                   9103:     $cmd = &escape($cmd);
                   9104:     my $query = 'institutionalphotos';
                   9105:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9106:     unless ($queryid=~/^\Q$host\E\_/) {
                   9107:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9108:         return 'error: '.$queryid;
                   9109:     }
                   9110:     my $reply = &get_query_reply($queryid);
                   9111:     my $tries = 1;
                   9112:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9113:         $reply = &get_query_reply($queryid);
                   9114:         $tries ++;
                   9115:     }
                   9116:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9117:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9118:     } else {
                   9119:         my @responses = split(/:/,$reply);
                   9120:         my $outcome = shift(@responses); 
                   9121:         foreach my $item (@responses) {
                   9122:             my ($key,$value) = split(/=/,$item);
                   9123:             $$photo{$key} = $value;
                   9124:         }
                   9125:         return $outcome;
                   9126:     }
                   9127:     return 'error';
                   9128: }
                   9129: 
1.521     raeburn  9130: sub auto_instcode_format {
1.793     albertel 9131:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9132: 	$cat_order) = @_;
1.521     raeburn  9133:     my $courses = '';
1.772     raeburn  9134:     my @homeservers;
1.521     raeburn  9135:     if ($caller eq 'global') {
1.841     albertel 9136: 	my %servers = &get_servers($codedom,'library');
                   9137: 	foreach my $tryserver (keys(%servers)) {
                   9138: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9139: 		push(@homeservers,$tryserver);
                   9140: 	    }
1.584     raeburn  9141:         }
1.1022    raeburn  9142:     } elsif ($caller eq 'requests') {
                   9143:         if ($codedom =~ /^$match_domain$/) {
                   9144:             my $chome = &domain($codedom,'primary');
                   9145:             unless ($chome eq 'no_host') {
                   9146:                 push(@homeservers,$chome);
                   9147:             }
                   9148:         }
1.521     raeburn  9149:     } else {
1.772     raeburn  9150:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9151:     }
1.793     albertel 9152:     foreach my $code (keys(%{$instcodes})) {
                   9153:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9154:     }
                   9155:     chop($courses);
1.772     raeburn  9156:     my $ok_response = 0;
                   9157:     my $response;
                   9158:     while (@homeservers > 0 && $ok_response == 0) {
                   9159:         my $server = shift(@homeservers); 
                   9160:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9161:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9162:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9163: 		split(/:/,$response);
1.772     raeburn  9164:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9165:             push(@{$codetitles},&str2array($codetitles_str));
                   9166:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9167:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9168:             $ok_response = 1;
                   9169:         }
                   9170:     }
                   9171:     if ($ok_response) {
1.521     raeburn  9172:         return 'ok';
1.772     raeburn  9173:     } else {
                   9174:         return $response;
1.521     raeburn  9175:     }
                   9176: }
                   9177: 
1.792     raeburn  9178: sub auto_instcode_defaults {
                   9179:     my ($domain,$returnhash,$code_order) = @_;
                   9180:     my @homeservers;
1.841     albertel 9181: 
                   9182:     my %servers = &get_servers($domain,'library');
                   9183:     foreach my $tryserver (keys(%servers)) {
                   9184: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9185: 	    push(@homeservers,$tryserver);
                   9186: 	}
1.792     raeburn  9187:     }
1.841     albertel 9188: 
1.792     raeburn  9189:     my $response;
1.841     albertel 9190:     foreach my $server (@homeservers) {
1.792     raeburn  9191:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9192:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9193: 	
                   9194: 	foreach my $pair (split(/\&/,$response)) {
                   9195: 	    my ($name,$value)=split(/\=/,$pair);
                   9196: 	    if ($name eq 'code_order') {
                   9197: 		@{$code_order} = split(/\&/,&unescape($value));
                   9198: 	    } else {
                   9199: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9200: 	    }
                   9201: 	}
                   9202: 	return 'ok';
1.792     raeburn  9203:     }
1.841     albertel 9204: 
                   9205:     return $response;
1.1003    raeburn  9206: }
                   9207: 
                   9208: sub auto_possible_instcodes {
1.1007    raeburn  9209:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9210:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9211:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9212:         return;
                   9213:     }
1.1003    raeburn  9214:     my (@homeservers,$uhome);
                   9215:     if (defined(&domain($domain,'primary'))) {
                   9216:         $uhome=&domain($domain,'primary');
                   9217:         push(@homeservers,&domain($domain,'primary'));
                   9218:     } else {
                   9219:         my %servers = &get_servers($domain,'library');
                   9220:         foreach my $tryserver (keys(%servers)) {
                   9221:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9222:                 push(@homeservers,$tryserver);
                   9223:             }
                   9224:         }
                   9225:     }
                   9226:     my $response;
                   9227:     foreach my $server (@homeservers) {
                   9228:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9229:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9230:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9231:             split(':',$response);
                   9232:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9233:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9234:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9235:             my ($name,$value)=split('=',$item);
                   9236:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9237:         }
                   9238:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9239:             my ($name,$value)=split('=',$item);
                   9240:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9241:         }
                   9242:         return 'ok';
                   9243:     }
                   9244:     return $response;
                   9245: }
1.792     raeburn  9246: 
1.1010    raeburn  9247: sub auto_courserequest_checks {
                   9248:     my ($dom) = @_;
1.1020    raeburn  9249:     my ($homeserver,%validations);
                   9250:     if ($dom =~ /^$match_domain$/) {
                   9251:         $homeserver = &domain($dom,'primary');
                   9252:     }
                   9253:     unless ($homeserver eq 'no_host') {
                   9254:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9255:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9256:             my @items = split(/&/,$response);
                   9257:             foreach my $item (@items) {
                   9258:                 my ($key,$value) = split('=',$item);
                   9259:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9260:             }
                   9261:         }
                   9262:     }
1.1010    raeburn  9263:     return %validations; 
                   9264: }
                   9265: 
1.1020    raeburn  9266: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9267:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9268:     my ($homeserver,$response);
                   9269:     if ($dom =~ /^$match_domain$/) {
                   9270:         $homeserver = &domain($dom,'primary');
                   9271:     }
1.1172.2.43  raeburn  9272:     unless ($homeserver eq 'no_host') {
                   9273:         my $customdata;
                   9274:         if (ref($custominfo) eq 'HASH') {
                   9275:             $customdata = &freeze_escape($custominfo);
                   9276:         }
1.1020    raeburn  9277:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9278:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9279:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9280:                                     $customdata,$homeserver));
1.1020    raeburn  9281:     }
                   9282:     return $response;
                   9283: }
                   9284: 
1.777     albertel 9285: sub auto_validate_class_sec {
1.918     raeburn  9286:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9287:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9288:     my $ownerlist;
                   9289:     if (ref($owners) eq 'ARRAY') {
                   9290:         $ownerlist = join(',',@{$owners});
                   9291:     } else {
                   9292:         $ownerlist = $owners;
                   9293:     }
1.773     raeburn  9294:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9295:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9296:     return $response;
                   9297: }
                   9298: 
1.1172.2.94  raeburn  9299: sub auto_validate_instclasses {
                   9300:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9301:     my ($homeserver,%validations);
                   9302:     $homeserver = &homeserver($cnum,$cdom);
                   9303:     unless ($homeserver eq 'no_host') {
                   9304:         my $ownerlist;
                   9305:         if (ref($owners) eq 'ARRAY') {
                   9306:             $ownerlist = join(',',@{$owners});
                   9307:         } else {
                   9308:             $ownerlist = $owners;
                   9309:         }
                   9310:         if (ref($classesref) eq 'HASH') {
                   9311:             my $classes = &freeze_escape($classesref);
                   9312:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9313:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9314:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9315:                 my @items = split(/&/,$response);
                   9316:                 foreach my $item (@items) {
                   9317:                     my ($key,$value) = split('=',$item);
                   9318:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9319:                 }
                   9320:             }
                   9321:         }
                   9322:     }
                   9323:     return %validations;
                   9324: }
                   9325: 
1.1172.2.38  raeburn  9326: sub auto_crsreq_update {
                   9327:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9328:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9329:     my ($homeserver,%crsreqresponse);
                   9330:     if ($cdom =~ /^$match_domain$/) {
                   9331:         $homeserver = &domain($cdom,'primary');
                   9332:     }
                   9333:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9334:         my $info;
                   9335:         if (ref($inbound) eq 'HASH') {
                   9336:             $info = &freeze_escape($inbound);
                   9337:         }
                   9338:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9339:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9340:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9341:                             &escape($title).':'.&escape($code).':'.
                   9342:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9343:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9344:             my @items = split(/&/,$response);
                   9345:             foreach my $item (@items) {
                   9346:                 my ($key,$value) = split('=',$item);
                   9347:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9348:             }
                   9349:         }
                   9350:     }
                   9351:     return \%crsreqresponse;
                   9352: }
                   9353: 
1.1172.2.78  raeburn  9354: sub auto_export_grades {
                   9355:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9356:     my ($homeserver,%exportresponse);
                   9357:     if ($cdom =~ /^$match_domain$/) {
                   9358:         $homeserver = &domain($cdom,'primary');
                   9359:     }
                   9360:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9361:         my $info;
                   9362:         if (ref($inforef) eq 'HASH') {
                   9363:             $info = &freeze_escape($inforef);
                   9364:         }
                   9365:         if (ref($gradesref) eq 'HASH') {
                   9366:             my $grades = &freeze_escape($gradesref);
                   9367:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9368:                                 $info.':'.$grades,$homeserver);
                   9369:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9370:                 my @items = split(/&/,$response);
                   9371:                 foreach my $item (@items) {
                   9372:                     my ($key,$value) = split('=',$item);
                   9373:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9374:                 }
                   9375:             }
                   9376:         }
                   9377:     }
                   9378:     return \%exportresponse;
                   9379: }
                   9380: 
1.1172.2.68  raeburn  9381: sub check_instcode_cloning {
                   9382:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9383:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9384:         return;
                   9385:     }
                   9386:     my $canclone;
                   9387:     if (@{$code_order} > 0) {
                   9388:         my $instcoderegexp ='^';
                   9389:         my @clonecodes = split(/\&/,$cloner);
                   9390:         foreach my $item (@{$code_order}) {
                   9391:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9392:                 foreach my $pair (@clonecodes) {
                   9393:                     my ($key,$val) = split(/\=/,$pair,2);
                   9394:                     $val = &unescape($val);
                   9395:                     if ($key eq $item) {
                   9396:                         $instcoderegexp .= '('.$val.')';
                   9397:                         last;
                   9398:                     }
                   9399:                 }
                   9400:             } else {
                   9401:                 $instcoderegexp .= $codedefaults->{$item};
                   9402:             }
                   9403:         }
                   9404:         $instcoderegexp .= '$';
                   9405:         my (@from,@to);
                   9406:         eval {
                   9407:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9408:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9409:         };
                   9410:         if ((@from > 0) && (@to > 0)) {
                   9411:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9412:             if (!@diffs) {
                   9413:                 $canclone = 1;
                   9414:             }
                   9415:         }
                   9416:     }
                   9417:     return $canclone;
                   9418: }
                   9419: 
                   9420: sub default_instcode_cloning {
                   9421:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9422:     my (%codedefaults,@code_order,$canclone);
                   9423:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9424:         %codedefaults = %{$codedefaultsref};
                   9425:         @code_order = @{$codeorderref};
                   9426:     } elsif ($clonedom) {
                   9427:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9428:     }
                   9429:     if (($domdefclone) && (@code_order)) {
                   9430:         my @clonecodes = split(/\+/,$domdefclone);
                   9431:         my $instcoderegexp ='^';
                   9432:         foreach my $item (@code_order) {
                   9433:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9434:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9435:             } else {
                   9436:                 $instcoderegexp .= $codedefaults{$item};
                   9437:             }
                   9438:         }
                   9439:         $instcoderegexp .= '$';
                   9440:         my (@from,@to);
                   9441:         eval {
                   9442:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9443:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9444:         };
                   9445:         if ((@from > 0) && (@to > 0)) {
                   9446:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9447:             if (!@diffs) {
                   9448:                 $canclone = 1;
                   9449:             }
                   9450:         }
                   9451:     }
                   9452:     return $canclone;
                   9453: }
                   9454: 
1.679     raeburn  9455: # ------------------------------------------------------- Course Group routines
                   9456: 
                   9457: sub get_coursegroups {
1.809     raeburn  9458:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9459:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9460: }
                   9461: 
1.679     raeburn  9462: sub modify_coursegroup {
                   9463:     my ($cdom,$cnum,$groupsettings) = @_;
                   9464:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9465: }
                   9466: 
1.809     raeburn  9467: sub toggle_coursegroup_status {
                   9468:     my ($cdom,$cnum,$group,$action) = @_;
                   9469:     my ($from_namespace,$to_namespace);
                   9470:     if ($action eq 'delete') {
                   9471:         $from_namespace = 'coursegroups';
                   9472:         $to_namespace = 'deleted_groups';
                   9473:     } else {
                   9474:         $from_namespace = 'deleted_groups';
                   9475:         $to_namespace = 'coursegroups';
                   9476:     }
                   9477:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9478:     if (my $tmp = &error(%curr_group)) {
                   9479:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9480:         return ('read error',$tmp);
                   9481:     } else {
                   9482:         my %savedsettings = %curr_group; 
1.809     raeburn  9483:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9484:         my $deloutcome;
                   9485:         if ($result eq 'ok') {
1.809     raeburn  9486:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9487:         } else {
                   9488:             return ('write error',$result);
                   9489:         }
                   9490:         if ($deloutcome eq 'ok') {
                   9491:             return 'ok';
                   9492:         } else {
                   9493:             return ('delete error',$deloutcome);
                   9494:         }
                   9495:     }
                   9496: }
                   9497: 
1.679     raeburn  9498: sub modify_group_roles {
1.957     raeburn  9499:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9500:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9501:     my $role = 'gr/'.&escape($userprivs);
                   9502:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9503:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9504:     if ($result eq 'ok') {
                   9505:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9506:     }
1.679     raeburn  9507:     return $result;
                   9508: }
                   9509: 
                   9510: sub modify_coursegroup_membership {
                   9511:     my ($cdom,$cnum,$membership) = @_;
                   9512:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9513:     return $result;
                   9514: }
                   9515: 
1.682     raeburn  9516: sub get_active_groups {
                   9517:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9518:     my $now = time;
                   9519:     my %groups = ();
                   9520:     foreach my $key (keys(%env)) {
1.811     albertel 9521:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9522:             my ($start,$end) = split(/\./,$env{$key});
                   9523:             if (($end!=0) && ($end<$now)) { next; }
                   9524:             if (($start!=0) && ($start>$now)) { next; }
                   9525:             if ($1 eq $cdom && $2 eq $cnum) {
                   9526:                 $groups{$3} = $env{$key} ;
                   9527:             }
                   9528:         }
                   9529:     }
                   9530:     return %groups;
                   9531: }
                   9532: 
1.683     raeburn  9533: sub get_group_membership {
                   9534:     my ($cdom,$cnum,$group) = @_;
                   9535:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9536: }
                   9537: 
                   9538: sub get_users_groups {
                   9539:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9540:     my @usersgroups;
1.683     raeburn  9541:     my $cachetime=1800;
                   9542: 
                   9543:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9544:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9545:     if (defined($cached)) {
1.734     albertel 9546:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9547:     } else {  
                   9548:         $grouplist = '';
1.816     raeburn  9549:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9550:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9551:         my $access_end = $env{'course.'.$courseid.
                   9552:                               '.default_enrollment_end_date'};
                   9553:         my $now = time;
                   9554:         foreach my $key (keys(%roleshash)) {
                   9555:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9556:                 my $group = $1;
                   9557:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9558:                     my $start = $2;
                   9559:                     my $end = $1;
                   9560:                     if ($start == -1) { next; } # deleted from group
                   9561:                     if (($start!=0) && ($start>$now)) { next; }
                   9562:                     if (($end!=0) && ($end<$now)) {
                   9563:                         if ($access_end && $access_end < $now) {
                   9564:                             if ($access_end - $end < 86400) {
                   9565:                                 push(@usersgroups,$group);
1.733     raeburn  9566:                             }
                   9567:                         }
1.817     raeburn  9568:                         next;
1.733     raeburn  9569:                     }
1.817     raeburn  9570:                     push(@usersgroups,$group);
1.683     raeburn  9571:                 }
                   9572:             }
                   9573:         }
1.817     raeburn  9574:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9575:         $grouplist = join(':',@usersgroups);
                   9576:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9577:     }
1.733     raeburn  9578:     return @usersgroups;
1.683     raeburn  9579: }
                   9580: 
                   9581: sub devalidate_getgroups_cache {
                   9582:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9583:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9584: 
1.683     raeburn  9585:     my $hashid="$udom:$uname:$courseid";
                   9586:     &devalidate_cache_new('getgroups',$hashid);
                   9587: }
                   9588: 
1.12      www      9589: # ------------------------------------------------------------------ Plain Text
                   9590: 
                   9591: sub plaintext {
1.988     raeburn  9592:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9593:     if ($short =~ m{^cr/}) {
1.758     albertel 9594: 	return (split('/',$short))[-1];
                   9595:     }
1.742     raeburn  9596:     if (!defined($cid)) {
                   9597:         $cid = $env{'request.course.id'};
                   9598:     }
                   9599:     my %rolenames = (
1.1008    raeburn  9600:                       Course    => 'std',
                   9601:                       Community => 'alt1',
1.742     raeburn  9602:                     );
1.1037    raeburn  9603:     if ($cid ne '') {
                   9604:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9605:             unless ($forcedefault) {
                   9606:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9607:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9608:                 return &Apache::lonlocal::mt($roletext);
                   9609:             }
                   9610:         }
                   9611:     }
                   9612:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9613:         (defined($rolenames{$type})) && 
                   9614:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9615:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9616:     } elsif ($cid ne '') {
                   9617:         my $crstype = $env{'course.'.$cid.'.type'};
                   9618:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9619:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9620:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9621:         }
1.742     raeburn  9622:     }
1.1037    raeburn  9623:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9624: }
                   9625: 
                   9626: # ----------------------------------------------------------------- Assign Role
                   9627: 
                   9628: sub assignrole {
1.957     raeburn  9629:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9630:         $context)=@_;
1.21      www      9631:     my $mrole;
                   9632:     if ($role =~ /^cr\//) {
1.393     www      9633:         my $cwosec=$url;
1.811     albertel 9634:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9635: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9636:            my $refused = 1;
                   9637:            if ($context eq 'requestcourses') {
                   9638:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9639:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9640:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9641:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9642:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9643:                            if ($crsenv{'internal.courseowner'} eq
                   9644:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9645:                                $refused = '';
                   9646:                            }
                   9647:                        }
                   9648:                    }
                   9649:                }
                   9650:            }
                   9651:            if ($refused) {
                   9652:                &logthis('Refused custom assignrole: '.
                   9653:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9654:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9655:                return 'refused';
                   9656:            }
1.104     www      9657:         }
1.21      www      9658:         $mrole='cr';
1.678     raeburn  9659:     } elsif ($role =~ /^gr\//) {
                   9660:         my $cwogrp=$url;
1.811     albertel 9661:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9662:         unless (&allowed('mdg',$cwogrp)) {
                   9663:             &logthis('Refused group assignrole: '.
                   9664:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9665:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9666:             return 'refused';
                   9667:         }
                   9668:         $mrole='gr';
1.21      www      9669:     } else {
1.82      www      9670:         my $cwosec=$url;
1.811     albertel 9671:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9672:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9673:             my $refused;
                   9674:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9675:                 if (!(&allowed('c'.$role,$url))) {
                   9676:                     $refused = 1;
                   9677:                 }
                   9678:             } else {
                   9679:                 $refused = 1;
                   9680:             }
1.947     raeburn  9681:             if ($refused) {
1.1045    raeburn  9682:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9683:                 if (!$selfenroll && $context eq 'course') {
                   9684:                     my %crsenv;
                   9685:                     if ($role eq 'cc' || $role eq 'co') {
                   9686:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9687:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9688:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9689:                                 if ($crsenv{'internal.courseowner'} eq 
                   9690:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9691:                                     $refused = '';
                   9692:                                 }
                   9693:                             }
                   9694:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9695:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9696:                                 if ($crsenv{'internal.courseowner'} eq 
                   9697:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9698:                                     $refused = '';
                   9699:                                 }
                   9700:                             }
                   9701:                         }
                   9702:                     }
                   9703:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9704:                     $refused = '';
1.1017    raeburn  9705:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9706:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9707:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9708:                         my $wrongcc;
                   9709:                         if ($cnum =~ /^$match_community$/) {
                   9710:                             $wrongcc = 1 if ($role eq 'cc');
                   9711:                         } else {
                   9712:                             $wrongcc = 1 if ($role eq 'co');
                   9713:                         }
                   9714:                         unless ($wrongcc) {
                   9715:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9716:                             if ($crsenv{'internal.courseowner'} eq 
                   9717:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9718:                                 $refused = '';
                   9719:                             }
1.1017    raeburn  9720:                         }
                   9721:                     }
1.1172.2.9  raeburn  9722:                 } elsif ($context eq 'requestauthor') {
                   9723:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9724:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9725:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9726:                             $refused = '';
                   9727:                         } else {
                   9728:                             my %domdefaults = &get_domain_defaults($udom);
                   9729:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9730:                                 my $checkbystatus;
                   9731:                                 if ($env{'user.adv'}) {
                   9732:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9733:                                     if ($disposition eq 'automatic') {
                   9734:                                         $refused = '';
                   9735:                                     } elsif ($disposition eq '') {
                   9736:                                         $checkbystatus = 1;
                   9737:                                     }
                   9738:                                 } else {
                   9739:                                     $checkbystatus = 1;
                   9740:                                 }
                   9741:                                 if ($checkbystatus) {
                   9742:                                     if ($env{'environment.inststatus'}) {
                   9743:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9744:                                         foreach my $type (@inststatuses) {
                   9745:                                             if (($type ne '') &&
                   9746:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9747:                                                 $refused = '';
                   9748:                                             }
                   9749:                                         }
                   9750:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9751:                                         $refused = '';
                   9752:                                     }
                   9753:                                 }
                   9754:                             }
                   9755:                         }
                   9756:                     }
1.1017    raeburn  9757:                 }
                   9758:                 if ($refused) {
1.947     raeburn  9759:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9760:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9761: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9762:                     return 'refused';
                   9763:                 }
1.932     raeburn  9764:             }
1.1131    raeburn  9765:         } elsif ($role eq 'au') {
                   9766:             if ($url ne '/'.$udom.'/') {
                   9767:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9768:                          ' to assign author role for '.$uname.':'.$udom.
                   9769:                          ' in domain: '.$url.' refused (wrong domain).');
                   9770:                 return 'refused';
                   9771:             }
1.104     www      9772:         }
1.21      www      9773:         $mrole=$role;
                   9774:     }
1.620     albertel 9775:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9776:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9777:     if ($end) { $command.='_'.$end; }
1.21      www      9778:     if ($start) {
                   9779: 	if ($end) { 
1.81      www      9780:            $command.='_'.$start; 
1.21      www      9781:         } else {
1.81      www      9782:            $command.='_0_'.$start;
1.21      www      9783:         }
                   9784:     }
1.739     raeburn  9785:     my $origstart = $start;
                   9786:     my $origend = $end;
1.957     raeburn  9787:     my $delflag;
1.357     www      9788: # actually delete
                   9789:     if ($deleteflag) {
1.373     www      9790: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9791: # modify command to delete the role
1.620     albertel 9792:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9793:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9794: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9795: # set start and finish to negative values for userrolelog
                   9796:            $start=-1;
                   9797:            $end=-1;
1.957     raeburn  9798:            $delflag = 1;
1.357     www      9799:         }
                   9800:     }
                   9801: # send command
1.349     www      9802:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9803: # log new user role if status is ok
1.349     www      9804:     if ($answer eq 'ok') {
1.663     raeburn  9805: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9806:         if (($role eq 'cc') || ($role eq 'in') ||
                   9807:             ($role eq 'ep') || ($role eq 'ad') ||
                   9808:             ($role eq 'ta') || ($role eq 'st') ||
                   9809:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9810:             ($role eq 'co')) {
1.1172.2.13  raeburn  9811: # for course roles, perform group memberships changes triggered by role change.
                   9812:             unless ($role =~ /^gr/) {
                   9813:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9814:                                                  $origstart,$selfenroll,$context);
                   9815:             }
1.1172.2.9  raeburn  9816:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9817:                            $selfenroll,$context);
                   9818:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9819:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9820:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9821:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9822:                            $context);
                   9823:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9824:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9825:                              $context);
                   9826:         }
1.1053    raeburn  9827:         if ($role eq 'cc') {
                   9828:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9829:         }
1.349     www      9830:     }
                   9831:     return $answer;
1.169     harris41 9832: }
                   9833: 
1.1053    raeburn  9834: sub autoupdate_coowners {
                   9835:     my ($url,$end,$start,$uname,$udom) = @_;
                   9836:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9837:     if (($cdom ne '') && ($cnum ne '')) {
                   9838:         my $now = time;
                   9839:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9840:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9841:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9842:             my $instcode = $coursehash{'internal.coursecode'};
                   9843:             if ($instcode ne '') {
1.1056    raeburn  9844:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9845:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9846:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9847:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9848:                         if ($result eq 'valid') {
                   9849:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9850:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9851:                                     push(@newcoowners,$coowner);
                   9852:                                 }
                   9853:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9854:                                     push(@newcoowners,$uname.':'.$udom);
                   9855:                                 }
                   9856:                                 @newcoowners = sort(@newcoowners);
                   9857:                             } else {
                   9858:                                 push(@newcoowners,$uname.':'.$udom);
                   9859:                             }
                   9860:                         } else {
                   9861:                             if ($coursehash{'internal.co-owners'}) {
                   9862:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9863:                                     unless ($coowner eq $uname.':'.$udom) {
                   9864:                                         push(@newcoowners,$coowner);
                   9865:                                     }
                   9866:                                 }
                   9867:                                 unless (@newcoowners > 0) {
                   9868:                                     $delcoowners = 1;
                   9869:                                     $coowners = '';
                   9870:                                 }
                   9871:                             }
                   9872:                         }
                   9873:                         if (@newcoowners || $delcoowners) {
                   9874:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9875:                                             $delcoowners,@newcoowners);
                   9876:                         }
                   9877:                     }
                   9878:                 }
                   9879:             }
                   9880:         }
                   9881:     }
                   9882: }
                   9883: 
                   9884: sub store_coowners {
                   9885:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9886:     my $cid = $cdom.'_'.$cnum;
                   9887:     my ($coowners,$delresult,$putresult);
                   9888:     if (@newcoowners) {
                   9889:         $coowners = join(',',@newcoowners);
                   9890:         my %coownershash = (
                   9891:                             'internal.co-owners' => $coowners,
                   9892:                            );
                   9893:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9894:         if ($putresult eq 'ok') {
                   9895:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9896:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9897:             }
                   9898:         }
                   9899:     }
                   9900:     if ($delcoowners) {
                   9901:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9902:         if ($delresult eq 'ok') {
                   9903:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9904:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9905:             }
                   9906:         }
                   9907:     }
                   9908:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9909:         my %crsinfo =
                   9910:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9911:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9912:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9913:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9914:         }
                   9915:     }
                   9916: }
                   9917: 
1.169     harris41 9918: # -------------------------------------------------- Modify user authentication
1.197     www      9919: # Overrides without validation
                   9920: 
1.169     harris41 9921: sub modifyuserauth {
                   9922:     my ($udom,$uname,$umode,$upass)=@_;
                   9923:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9924:     my $allowed;
                   9925:     if (&allowed('mau',$udom)) {
                   9926:         $allowed = 1;
                   9927:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9928:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9929:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9930:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9931:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9932:         if (($cdom ne '') && ($cnum ne '')) {
                   9933:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9934:             if ($is_owner) {
                   9935:                 $allowed = 1;
                   9936:             }
                   9937:         }
                   9938:     }
                   9939:     unless ($allowed) { return 'refused'; }
1.197     www      9940:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9941:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9942:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9943:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9944: 		     &escape($upass),$uhome);
1.620     albertel 9945:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9946:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9947:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9948:     &log($udom,,$uname,$uhome,
1.620     albertel 9949:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9950:                                      $env{'user.name'}.', '.$umode.
1.197     www      9951:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9952:     unless ($reply eq 'ok') {
1.197     www      9953:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9954: 	return 'error: '.$reply;
                   9955:     }   
1.170     harris41 9956:     return 'ok';
1.80      www      9957: }
                   9958: 
1.81      www      9959: # --------------------------------------------------------------- Modify a user
1.80      www      9960: 
1.81      www      9961: sub modifyuser {
1.206     matthew  9962:     my ($udom,    $uname, $uid,
                   9963:         $umode,   $upass, $first,
                   9964:         $middle,  $last,  $gene,
1.1058    raeburn  9965:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9966:     $udom= &LONCAPA::clean_domain($udom);
                   9967:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9968:     my $showcandelete = 'none';
                   9969:     if (ref($candelete) eq 'ARRAY') {
                   9970:         if (@{$candelete} > 0) {
                   9971:             $showcandelete = join(', ',@{$candelete});
                   9972:         }
                   9973:     }
1.81      www      9974:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9975:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9976: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9977:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9978:                                      ' desiredhome not specified'). 
1.620     albertel 9979:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9980:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9981:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9982:     my $newuser;
                   9983:     if ($uhome eq 'no_host') {
                   9984:         $newuser = 1;
                   9985:     }
1.80      www      9986: # ----------------------------------------------------------------- Create User
1.406     albertel 9987:     if (($uhome eq 'no_host') && 
                   9988: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9989:         my $unhome='';
1.844     albertel 9990:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9991:             $unhome = $desiredhome;
1.620     albertel 9992: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9993: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9994:         } else { # load balancing routine for determining $unhome
1.81      www      9995:             my $loadm=10000000;
1.841     albertel 9996: 	    my %servers = &get_servers($udom,'library');
                   9997: 	    foreach my $tryserver (keys(%servers)) {
                   9998: 		my $answer=reply('load',$tryserver);
                   9999: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10000: 		    $loadm=$answer;
                   10001: 		    $unhome=$tryserver;
                   10002: 		}
1.80      www      10003: 	    }
                   10004:         }
                   10005:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10006: 	    return 'error: unable to find a home server for '.$uname.
                   10007:                    ' in domain '.$udom;
1.80      www      10008:         }
                   10009:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10010:                          &escape($upass),$unhome);
                   10011: 	unless ($reply eq 'ok') {
                   10012:             return 'error: '.$reply;
                   10013:         }   
1.230     stredwic 10014:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10015:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10016: 	    return 'error: unable verify users home machine.';
1.80      www      10017:         }
1.209     matthew  10018:     }   # End of creation of new user
1.80      www      10019: # ---------------------------------------------------------------------- Add ID
                   10020:     if ($uid) {
                   10021:        $uid=~tr/A-Z/a-z/;
                   10022:        my %uidhash=&idrget($udom,$uname);
1.196     www      10023:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10024:          && (!$forceid)) {
1.80      www      10025: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10026: 	      return 'error: user id "'.$uid.'" does not match '.
                   10027:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10028:           }
                   10029:        } else {
                   10030: 	  &idput($udom,($uname => $uid));
                   10031:        }
                   10032:     }
                   10033: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10034:     my @tmp=&get('environment',
1.899     raeburn  10035: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10036:                     'permanentemail','inststatus'],
1.134     albertel 10037: 		   $udom,$uname);
1.1075    raeburn  10038:     my (%names,%oldnames);
1.313     matthew  10039:     if ($tmp[0] =~ m/^error:.*/) { 
                   10040:         %names=(); 
                   10041:     } else {
                   10042:         %names = @tmp;
1.1075    raeburn  10043:         %oldnames = %names;
1.313     matthew  10044:     }
1.388     www      10045: #
1.1058    raeburn  10046: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10047: # of users did not contain them), do not overwrite existing values
                   10048: # unless field is in $candelete array ref.  
                   10049: #
                   10050: 
                   10051:     my @fields = ('firstname','middlename','lastname','generation',
                   10052:                   'permanentemail','id');
                   10053:     my %newvalues;
                   10054:     if (ref($candelete) eq 'ARRAY') {
                   10055:         foreach my $field (@fields) {
                   10056:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10057:                 if ($field eq 'firstname') {
                   10058:                     $names{$field} = $first;
                   10059:                 } elsif ($field eq 'middlename') {
                   10060:                     $names{$field} = $middle;
                   10061:                 } elsif ($field eq 'lastname') {
                   10062:                     $names{$field} = $last;
                   10063:                 } elsif ($field eq 'generation') { 
                   10064:                     $names{$field} = $gene;
                   10065:                 } elsif ($field eq 'permanentemail') {
                   10066:                     $names{$field} = $email;
                   10067:                 } elsif ($field eq 'id') {
                   10068:                     $names{$field}  = $uid;
                   10069:                 }
                   10070:             }
                   10071:         }
                   10072:     }
1.388     www      10073:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10074:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10075:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10076:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10077:     if ($email) {
                   10078:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10079:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10080:     }
1.899     raeburn  10081:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10082:     if (defined($inststatus)) {
                   10083:         $names{'inststatus'} = '';
                   10084:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10085:         if (ref($usertypes) eq 'HASH') {
                   10086:             my @okstatuses; 
                   10087:             foreach my $item (split(/:/,$inststatus)) {
                   10088:                 if (defined($usertypes->{$item})) {
                   10089:                     push(@okstatuses,$item);  
                   10090:                 }
                   10091:             }
                   10092:             if (@okstatuses) {
                   10093:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10094:             }
                   10095:         }
                   10096:     }
1.1075    raeburn  10097:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10098:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10099:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10100:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10101:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10102:     } else {
                   10103:         $logmsg .= ' during self creation';
                   10104:     }
1.1075    raeburn  10105:     my $changed;
                   10106:     if ($newuser) {
                   10107:         $changed = 1;
                   10108:     } else {
                   10109:         foreach my $field (@fields) {
                   10110:             if ($names{$field} ne $oldnames{$field}) {
                   10111:                 $changed = 1;
                   10112:                 last;
                   10113:             }
                   10114:         }
                   10115:     }
                   10116:     unless ($changed) {
                   10117:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10118:         &logthis($logmsg);
                   10119:         return 'ok';
                   10120:     }
                   10121:     my $reply = &put('environment', \%names, $udom,$uname);
                   10122:     if ($reply ne 'ok') { 
                   10123:         return 'error: '.$reply;
                   10124:     }
1.1087    raeburn  10125:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10126:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10127:     }
1.1075    raeburn  10128:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10129:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10130:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10131:     &logthis($logmsg);
1.134     albertel 10132:     return 'ok';
1.80      www      10133: }
                   10134: 
1.81      www      10135: # -------------------------------------------------------------- Modify student
1.80      www      10136: 
1.81      www      10137: sub modifystudent {
                   10138:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10139:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10140:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10141:     if (!$cid) {
1.620     albertel 10142: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10143: 	    return 'not_in_class';
                   10144: 	}
1.80      www      10145:     }
                   10146: # --------------------------------------------------------------- Make the user
1.81      www      10147:     my $reply=&modifyuser
1.209     matthew  10148: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10149:          $desiredhome,$email,$inststatus);
1.80      www      10150:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10151:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10152:     # student's environment
1.297     matthew  10153:     $uid = undef if (!$forceid);
1.455     albertel 10154:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10155: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10156:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10157:     return $reply;
                   10158: }
                   10159: 
                   10160: sub modify_student_enrollment {
1.1172.2.23  raeburn  10161:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10162:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10163:     my ($cdom,$cnum,$chome);
                   10164:     if (!$cid) {
1.620     albertel 10165: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10166: 	    return 'not_in_class';
                   10167: 	}
1.620     albertel 10168: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10169: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10170:     } else {
                   10171: 	($cdom,$cnum)=split(/_/,$cid);
                   10172:     }
1.620     albertel 10173:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10174:     if (!$chome) {
1.457     raeburn  10175: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10176:     }
1.455     albertel 10177:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10178:     # Make sure the user exists
1.81      www      10179:     my $uhome=&homeserver($uname,$udom);
                   10180:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10181: 	return 'error: no such user';
                   10182:     }
1.297     matthew  10183:     # Get student data if we were not given enough information
                   10184:     if (!defined($first)  || $first  eq '' || 
                   10185:         !defined($last)   || $last   eq '' || 
                   10186:         !defined($uid)    || $uid    eq '' || 
                   10187:         !defined($middle) || $middle eq '' || 
                   10188:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10189:         # They did not supply us with enough data to enroll the student, so
                   10190:         # we need to pick up more information.
1.297     matthew  10191:         my %tmp = &get('environment',
1.294     matthew  10192:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10193:                        ,$udom,$uname);
                   10194: 
1.800     albertel 10195:         #foreach my $key (keys(%tmp)) {
                   10196:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10197:         #}
1.294     matthew  10198:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10199:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10200:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10201:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10202:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10203:     }
1.556     albertel 10204:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10205:     my $user = "$uname:$udom";
                   10206:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10207:     my $reply=cput('classlist',
1.1148    raeburn  10208: 		   {$user => 
1.1172.2.76  raeburn  10209: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10210: 		   $cdom,$cnum);
1.1148    raeburn  10211:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10212:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10213:     } else { 
1.81      www      10214: 	return 'error: '.$reply;
                   10215:     }
1.297     matthew  10216:     # Add student role to user
1.83      www      10217:     my $uurl='/'.$cid;
1.81      www      10218:     $uurl=~s/\_/\//g;
                   10219:     if ($usec) {
                   10220: 	$uurl.='/'.$usec;
                   10221:     }
1.1148    raeburn  10222:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10223:                              $selfenroll,$context);
                   10224:     if ($result ne 'ok') {
                   10225:         if ($old_entry{$user} ne '') {
                   10226:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10227:         } else {
                   10228:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10229:         }
                   10230:     }
                   10231:     return $result; 
1.21      www      10232: }
                   10233: 
1.556     albertel 10234: sub format_name {
                   10235:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10236:     my $name;
                   10237:     if ($first ne 'lastname') {
                   10238: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10239:     } else {
                   10240: 	if ($lastname=~/\S/) {
                   10241: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10242: 	    $name=~s/\s+,/,/;
                   10243: 	} else {
                   10244: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10245: 	}
                   10246:     }
                   10247:     $name=~s/^\s+//;
                   10248:     $name=~s/\s+$//;
                   10249:     $name=~s/\s+/ /g;
                   10250:     return $name;
                   10251: }
                   10252: 
1.84      www      10253: # ------------------------------------------------- Write to course preferences
                   10254: 
                   10255: sub writecoursepref {
                   10256:     my ($courseid,%prefs)=@_;
                   10257:     $courseid=~s/^\///;
                   10258:     $courseid=~s/\_/\//g;
                   10259:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10260:     my $chome=homeserver($cnum,$cdomain);
                   10261:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10262: 	return 'error: no such course';
                   10263:     }
                   10264:     my $cstring='';
1.800     albertel 10265:     foreach my $pref (keys(%prefs)) {
                   10266: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10267:     }
1.84      www      10268:     $cstring=~s/\&$//;
                   10269:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10270: }
                   10271: 
                   10272: # ---------------------------------------------------------- Make/modify course
                   10273: 
                   10274: sub createcourse {
1.741     raeburn  10275:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10276:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10277:     $url=&declutter($url);
                   10278:     my $cid='';
1.1028    raeburn  10279:     if ($context eq 'requestcourses') {
                   10280:         my $can_create = 0;
                   10281:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10282:         if ($udom eq $ownerdom) {
                   10283:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10284:                                   $context)) {
                   10285:                 $can_create = 1;
                   10286:             }
                   10287:         } else {
                   10288:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10289:                                            $category);
                   10290:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10291:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10292:                 if (@curr > 0) {
                   10293:                     my @options = qw(approval validate autolimit);
                   10294:                     my $optregex = join('|',@options);
                   10295:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10296:                         $can_create = 1;
                   10297:                     }
                   10298:                 }
                   10299:             }
                   10300:         }
                   10301:         if ($can_create) {
                   10302:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10303:                 unless (&allowed('ccc',$udom)) {
                   10304:                     return 'refused'; 
                   10305:                 }
1.1017    raeburn  10306:             }
                   10307:         } else {
                   10308:             return 'refused';
                   10309:         }
1.1028    raeburn  10310:     } elsif (!&allowed('ccc',$udom)) {
                   10311:         return 'refused';
1.84      www      10312:     }
1.1011    raeburn  10313: # --------------------------------------------------------------- Get Unique ID
                   10314:     my $uname;
                   10315:     if ($cnum =~ /^$match_courseid$/) {
                   10316:         my $chome=&homeserver($cnum,$udom,'true');
                   10317:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10318:             $uname = $cnum;
                   10319:         } else {
1.1038    raeburn  10320:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10321:         }
                   10322:     } else {
1.1038    raeburn  10323:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10324:     }
                   10325:     return $uname if ($uname =~ /^error/);
                   10326: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10327:     if (!defined($course_server)) {
                   10328:         if (defined(&domain($udom,'primary'))) {
                   10329:             $course_server = &domain($udom,'primary');
                   10330:         } else {
                   10331:             $course_server = $env{'user.home'}; 
                   10332:         }
                   10333:     }
                   10334:     my %host_servers =
                   10335:         &Apache::lonnet::get_servers($udom,'library');
                   10336:     unless ($host_servers{$course_server}) {
                   10337:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10338:     }
1.84      www      10339: # ------------------------------------------------------------- Make the course
                   10340:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10341:                       $course_server);
1.84      www      10342:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10343:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10344:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10345: 	return 'error: no such course';
                   10346:     }
1.271     www      10347: # ----------------------------------------------------------------- Course made
1.516     raeburn  10348: # log existence
1.1029    raeburn  10349:     my $now = time;
1.918     raeburn  10350:     my $newcourse = {
                   10351:                     $udom.'_'.$uname => {
1.921     raeburn  10352:                                      description => $description,
                   10353:                                      inst_code   => $inst_code,
                   10354:                                      owner       => $course_owner,
                   10355:                                      type        => $crstype,
1.1029    raeburn  10356:                                      creator     => $env{'user.name'}.':'.
                   10357:                                                     $env{'user.domain'},
                   10358:                                      created     => $now,
                   10359:                                      context     => $context,
1.918     raeburn  10360:                                                 },
                   10361:                     };
1.921     raeburn  10362:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10363: # set toplevel url
1.271     www      10364:     my $topurl=$url;
                   10365:     unless ($nonstandard) {
                   10366: # ------------------------------------------ For standard courses, make top url
                   10367:         my $mapurl=&clutter($url);
1.278     www      10368:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10369:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10370: <map>
                   10371: <resource id="1" type="start"></resource>
                   10372: <resource id="2" src="$mapurl"></resource>
                   10373: <resource id="3" type="finish"></resource>
                   10374: <link index="1" from="1" to="2"></link>
                   10375: <link index="2" from="2" to="3"></link>
                   10376: </map>
                   10377: ENDINITMAP
                   10378:         $topurl=&declutter(
1.638     albertel 10379:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10380:                           );
                   10381:     }
                   10382: # ----------------------------------------------------------- Write preferences
1.84      www      10383:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10384:                      ('description'              => $description,
                   10385:                       'url'                      => $topurl,
                   10386:                       'internal.creator'         => $env{'user.name'}.':'.
                   10387:                                                     $env{'user.domain'},
                   10388:                       'internal.created'         => $now,
                   10389:                       'internal.creationcontext' => $context)
                   10390:                     );
1.84      www      10391:     return '/'.$udom.'/'.$uname;
                   10392: }
                   10393: 
1.1011    raeburn  10394: # ------------------------------------------------------------------- Create ID
                   10395: sub generate_coursenum {
1.1038    raeburn  10396:     my ($udom,$crstype) = @_;
1.1011    raeburn  10397:     my $domdesc = &domain($udom);
                   10398:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10399:     my $first;
                   10400:     if ($crstype eq 'Community') {
                   10401:         $first = '0';
                   10402:     } else {
                   10403:         $first = int(1+rand(9)); 
                   10404:     } 
                   10405:     my $uname=$first.
1.1011    raeburn  10406:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10407:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10408:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10409: # ----------------------------------------------- Make sure that does not exist
                   10410:     my $uhome=&homeserver($uname,$udom,'true');
                   10411:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10412:         if ($crstype eq 'Community') {
                   10413:             $first = '0';
                   10414:         } else {
                   10415:             $first = int(1+rand(9));
                   10416:         }
                   10417:         $uname=$first.
1.1011    raeburn  10418:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10419:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10420:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10421:         $uhome=&homeserver($uname,$udom,'true');
                   10422:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10423:             return 'error: unable to generate unique course-ID';
                   10424:         }
                   10425:     }
                   10426:     return $uname;
                   10427: }
                   10428: 
1.813     albertel 10429: sub is_course {
1.1167    droeschl 10430:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10431:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10432:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10433:     my $uhome=&homeserver($cnum,$cdom);
                   10434:     my $iscourse;
                   10435:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10436:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10437:     } else {
                   10438:         my $hashid = $cdom.':'.$cnum;
                   10439:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10440:         unless (defined($cached)) {
                   10441:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10442:                                         $cnum,undef,undef,'.');
                   10443:             $iscourse = 0;
                   10444:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10445:                 $iscourse = 1;
                   10446:             }
                   10447:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10448:         }
                   10449:     }
                   10450:     return unless($iscourse);
1.1167    droeschl 10451:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10452: }
                   10453: 
1.1015    raeburn  10454: sub store_userdata {
                   10455:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10456:     my $result;
1.1016    raeburn  10457:     if ($datakey ne '') {
1.1013    raeburn  10458:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10459:             if ($udom eq '' || $uname eq '') {
                   10460:                 $udom = $env{'user.domain'};
                   10461:                 $uname = $env{'user.name'};
                   10462:             }
                   10463:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10464:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10465:                 $result = 'error: no_host';
                   10466:             } else {
                   10467:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10468:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10469: 
                   10470:                 my $namevalue='';
                   10471:                 foreach my $key (keys(%{$storehash})) {
                   10472:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10473:                 }
                   10474:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10475:                 unless ($namespace eq 'courserequests') {
                   10476:                     $datakey = &escape($datakey);
                   10477:                 }
1.1105    raeburn  10478:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10479:                                   $namevalue,$uhome);
1.1013    raeburn  10480:             }
                   10481:         } else {
                   10482:             $result = 'error: data to store was not a hash reference'; 
                   10483:         }
                   10484:     } else {
                   10485:         $result= 'error: invalid requestkey'; 
                   10486:     }
                   10487:     return $result;
                   10488: }
                   10489: 
1.21      www      10490: # ---------------------------------------------------------- Assign Custom Role
                   10491: 
                   10492: sub assigncustomrole {
1.957     raeburn  10493:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10494:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10495:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10496: }
                   10497: 
                   10498: # ----------------------------------------------------------------- Revoke Role
                   10499: 
                   10500: sub revokerole {
1.957     raeburn  10501:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10502:     my $now=time;
1.965     raeburn  10503:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10504: }
                   10505: 
                   10506: # ---------------------------------------------------------- Revoke Custom Role
                   10507: 
                   10508: sub revokecustomrole {
1.957     raeburn  10509:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10510:     my $now=time;
1.357     www      10511:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10512:            $deleteflag,$selfenroll,$context);
1.17      www      10513: }
                   10514: 
1.533     banghart 10515: # ------------------------------------------------------------ Disk usage
1.535     albertel 10516: sub diskusage {
1.955     raeburn  10517:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10518:     $directorypath =~ s/\/$//;
                   10519:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10520:                        .&escape($getpropath).':'.&escape($uname).':'
                   10521:                        .&escape($udom),homeserver($uname,$udom));
                   10522:     if ($listing eq 'unknown_cmd') {
                   10523:         if ($getpropath) {
                   10524:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10525:         }
                   10526:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10527:     }
1.514     albertel 10528:     return $listing;
1.512     banghart 10529: }
                   10530: 
1.566     banghart 10531: sub is_locked {
1.1096    raeburn  10532:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10533:     my @check;
                   10534:     my $is_locked;
1.1093    raeburn  10535:     push (@check,$file_name);
1.613     albertel 10536:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10537: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10538:     my ($tmp)=keys(%locked);
                   10539:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10540:     
1.566     banghart 10541:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10542:         $is_locked = 'false';
                   10543:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10544:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10545:                $is_locked = 'true';
1.1096    raeburn  10546:                if (ref($which) eq 'ARRAY') {
                   10547:                    push(@{$which},$entry);
                   10548:                } else {
                   10549:                    last;
                   10550:                }
1.745     raeburn  10551:            }
                   10552:        }
1.566     banghart 10553:     } else {
                   10554:         $is_locked = 'false';
                   10555:     }
1.1093    raeburn  10556:     return $is_locked;
1.566     banghart 10557: }
                   10558: 
1.759     albertel 10559: sub declutter_portfile {
                   10560:     my ($file) = @_;
1.833     albertel 10561:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10562:     return $file;
                   10563: }
                   10564: 
1.559     banghart 10565: # ------------------------------------------------------------- Mark as Read Only
                   10566: 
                   10567: sub mark_as_readonly {
                   10568:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10569:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10570:     my ($tmp)=keys(%current_permissions);
                   10571:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10572:     foreach my $file (@{$files}) {
1.759     albertel 10573: 	$file = &declutter_portfile($file);
1.561     banghart 10574:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10575:     }
1.613     albertel 10576:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10577:     return;
                   10578: }
                   10579: 
1.572     banghart 10580: # ------------------------------------------------------------Save Selected Files
                   10581: 
                   10582: sub save_selected_files {
                   10583:     my ($user, $path, @files) = @_;
                   10584:     my $filename = $user."savedfiles";
1.573     banghart 10585:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10586:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10587:     foreach my $file (@files) {
1.620     albertel 10588:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10589:     }
                   10590:     foreach my $file (@other_files) {
1.574     banghart 10591:         print (OUT $file."\n");
1.572     banghart 10592:     }
1.574     banghart 10593:     close (OUT);
1.572     banghart 10594:     return 'ok';
                   10595: }
                   10596: 
1.574     banghart 10597: sub clear_selected_files {
                   10598:     my ($user) = @_;
                   10599:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10600:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10601:     print (OUT undef);
                   10602:     close (OUT);
                   10603:     return ("ok");    
                   10604: }
                   10605: 
1.572     banghart 10606: sub files_in_path {
                   10607:     my ($user, $path) = @_;
                   10608:     my $filename = $user."savedfiles";
                   10609:     my %return_files;
1.1172.2.96  raeburn  10610:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10611:     while (my $line_in = <IN>) {
1.574     banghart 10612:         chomp ($line_in);
                   10613:         my @paths_and_file = split (m!/!, $line_in);
                   10614:         my $file_part = pop (@paths_and_file);
                   10615:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10616:         $path_part.='/';
                   10617:         my $path_and_file = $path_part.$file_part;
                   10618:         if ($path_part eq $path) {
                   10619:             $return_files{$file_part}= 'selected';
                   10620:         }
                   10621:     }
1.574     banghart 10622:     close (IN);
                   10623:     return (\%return_files);
1.572     banghart 10624: }
                   10625: 
                   10626: # called in portfolio select mode, to show files selected NOT in current directory
                   10627: sub files_not_in_path {
                   10628:     my ($user, $path) = @_;
                   10629:     my $filename = $user."savedfiles";
                   10630:     my @return_files;
                   10631:     my $path_part;
1.1172.2.96  raeburn  10632:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10633:     while (my $line = <IN>) {
1.572     banghart 10634:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10635:         my @paths_and_file = split(m|/|, $line);
                   10636:         my $file_part = pop(@paths_and_file);
                   10637:         chomp($file_part);
                   10638:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10639:         $path_part .= '/';
                   10640:         my $path_and_file = $path_part.$file_part;
                   10641:         if ($path_part ne $path) {
1.800     albertel 10642:             push(@return_files, ($path_and_file));
1.572     banghart 10643:         }
                   10644:     }
1.800     albertel 10645:     close(OUT);
1.574     banghart 10646:     return (@return_files);
1.572     banghart 10647: }
                   10648: 
1.745     raeburn  10649: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10650: 
1.745     raeburn  10651: sub get_portfile_permissions {
                   10652:     my ($domain,$user) = @_;
1.613     albertel 10653:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10654:     my ($tmp)=keys(%current_permissions);
                   10655:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10656:     return \%current_permissions;
                   10657: }
                   10658: 
                   10659: #---------------------------------------------Get portfolio file access controls
                   10660: 
1.749     raeburn  10661: sub get_access_controls {
1.745     raeburn  10662:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10663:     my %access;
                   10664:     my $real_file = $file;
                   10665:     $file =~ s/\.meta$//;
1.745     raeburn  10666:     if (defined($file)) {
1.749     raeburn  10667:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10668:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10669:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10670:             }
                   10671:         }
1.745     raeburn  10672:     } else {
1.749     raeburn  10673:         foreach my $key (keys(%{$current_permissions})) {
                   10674:             if ($key =~ /\0accesscontrol$/) {
                   10675:                 if (defined($group)) {
                   10676:                     if ($key !~ m-^\Q$group\E/-) {
                   10677:                         next;
                   10678:                     }
                   10679:                 }
                   10680:                 my ($fullpath) = split(/\0/,$key);
                   10681:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10682:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10683:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10684:                     }
                   10685:                 }
                   10686:             }
                   10687:         }
                   10688:     }
                   10689:     return %access;
                   10690: }
                   10691: 
                   10692: sub modify_access_controls {
                   10693:     my ($file_name,$changes,$domain,$user)=@_;
                   10694:     my ($outcome,$deloutcome);
                   10695:     my %store_permissions;
                   10696:     my %new_values;
                   10697:     my %new_control;
                   10698:     my %translation;
                   10699:     my @deletions = ();
                   10700:     my $now = time;
                   10701:     if (exists($$changes{'activate'})) {
                   10702:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10703:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10704:             my $numnew = scalar(@newitems);
                   10705:             for (my $i=0; $i<$numnew; $i++) {
                   10706:                 my $newkey = $newitems[$i];
                   10707:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10708:                 if ($newkey =~ /^\d+:/) { 
                   10709:                     $newkey =~ s/^(\d+)/$newid/;
                   10710:                     $translation{$1} = $newid;
                   10711:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10712:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10713:                     $translation{$1} = $newid;
                   10714:                 }
1.749     raeburn  10715:                 $new_values{$file_name."\0".$newkey} = 
                   10716:                                           $$changes{'activate'}{$newitems[$i]};
                   10717:                 $new_control{$newkey} = $now;
                   10718:             }
                   10719:         }
                   10720:     }
                   10721:     my %todelete;
                   10722:     my %changed_items;
                   10723:     foreach my $action ('delete','update') {
                   10724:         if (exists($$changes{$action})) {
                   10725:             if (ref($$changes{$action}) eq 'HASH') {
                   10726:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10727:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10728:                     if ($action eq 'delete') { 
                   10729:                         $todelete{$itemnum} = 1;
                   10730:                     } else {
                   10731:                         $changed_items{$itemnum} = $key;
                   10732:                     }
                   10733:                 }
1.745     raeburn  10734:             }
                   10735:         }
1.749     raeburn  10736:     }
                   10737:     # get lock on access controls for file.
                   10738:     my $lockhash = {
                   10739:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10740:                                                        ':'.$env{'user.domain'},
                   10741:                    }; 
                   10742:     my $tries = 0;
                   10743:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10744:    
1.1172.2.79  raeburn  10745:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10746:         $tries ++;
1.1172.2.79  raeburn  10747:         sleep(0.1);
1.749     raeburn  10748:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10749:     }
                   10750:     if ($gotlock eq 'ok') {
                   10751:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10752:         my ($tmp)=keys(%curr_permissions);
                   10753:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10754:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10755:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10756:             if (ref($curr_controls) eq 'HASH') {
                   10757:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10758:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10759:                     if (defined($todelete{$itemnum})) {
                   10760:                         push(@deletions,$file_name."\0".$control_item);
                   10761:                     } else {
                   10762:                         if (defined($changed_items{$itemnum})) {
                   10763:                             $new_control{$changed_items{$itemnum}} = $now;
                   10764:                             push(@deletions,$file_name."\0".$control_item);
                   10765:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10766:                         } else {
                   10767:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10768:                         }
                   10769:                     }
1.745     raeburn  10770:                 }
                   10771:             }
                   10772:         }
1.970     raeburn  10773:         my ($group);
                   10774:         if (&is_course($domain,$user)) {
                   10775:             ($group,my $file) = split(/\//,$file_name,2);
                   10776:         }
1.749     raeburn  10777:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10778:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10779:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10780:         #  remove lock
                   10781:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10782:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10783:         my $sqlresult =
1.970     raeburn  10784:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10785:                                     $group);
1.749     raeburn  10786:     } else {
                   10787:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10788:     }
1.749     raeburn  10789:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10790: }
                   10791: 
1.827     raeburn  10792: sub make_public_indefinitely {
                   10793:     my ($requrl) = @_;
                   10794:     my $now = time;
                   10795:     my $action = 'activate';
                   10796:     my $aclnum = 0;
                   10797:     if (&is_portfolio_url($requrl)) {
                   10798:         my (undef,$udom,$unum,$file_name,$group) =
                   10799:             &parse_portfolio_url($requrl);
                   10800:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10801:         my %access_controls = &get_access_controls($current_perms,
                   10802:                                                    $group,$file_name);
                   10803:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10804:             my ($num,$scope,$end,$start) = 
                   10805:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10806:             if ($scope eq 'public') {
                   10807:                 if ($start <= $now && $end == 0) {
                   10808:                     $action = 'none';
                   10809:                 } else {
                   10810:                     $action = 'update';
                   10811:                     $aclnum = $num;
                   10812:                 }
                   10813:                 last;
                   10814:             }
                   10815:         }
                   10816:         if ($action eq 'none') {
                   10817:              return 'ok';
                   10818:         } else {
                   10819:             my %changes;
                   10820:             my $newend = 0;
                   10821:             my $newstart = $now;
                   10822:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10823:             $changes{$action}{$newkey} = {
                   10824:                 type => 'public',
                   10825:                 time => {
                   10826:                     start => $newstart,
                   10827:                     end   => $newend,
                   10828:                 },
                   10829:             };
                   10830:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10831:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10832:             return $outcome;
                   10833:         }
                   10834:     } else {
                   10835:         return 'invalid';
                   10836:     }
                   10837: }
                   10838: 
1.745     raeburn  10839: #------------------------------------------------------Get Marked as Read Only
                   10840: 
                   10841: sub get_marked_as_readonly {
                   10842:     my ($domain,$user,$what,$group) = @_;
                   10843:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10844:     my @readonly_files;
1.629     banghart 10845:     my $cmp1=$what;
                   10846:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10847:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10848:         if (defined($group)) {
                   10849:             if ($file_name !~ m-^\Q$group\E/-) {
                   10850:                 next;
                   10851:             }
                   10852:         }
1.561     banghart 10853:         if (ref($value) eq "ARRAY"){
                   10854:             foreach my $stored_what (@{$value}) {
1.629     banghart 10855:                 my $cmp2=$stored_what;
1.759     albertel 10856:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10857:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10858:                 }
1.629     banghart 10859:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10860:                     push(@readonly_files, $file_name);
1.745     raeburn  10861:                     last;
1.563     banghart 10862:                 } elsif (!defined($what)) {
                   10863:                     push(@readonly_files, $file_name);
1.745     raeburn  10864:                     last;
1.561     banghart 10865:                 }
                   10866:             }
1.745     raeburn  10867:         }
1.561     banghart 10868:     }
                   10869:     return @readonly_files;
                   10870: }
1.577     banghart 10871: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10872: 
1.577     banghart 10873: sub get_marked_as_readonly_hash {
1.745     raeburn  10874:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10875:     my %readonly_files;
1.745     raeburn  10876:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10877:         if (defined($group)) {
                   10878:             if ($file_name !~ m-^\Q$group\E/-) {
                   10879:                 next;
                   10880:             }
                   10881:         }
1.577     banghart 10882:         if (ref($value) eq "ARRAY"){
                   10883:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10884:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10885:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10886:                         if ($lock_descriptor eq 'graded') {
                   10887:                             $readonly_files{$file_name} = 'graded';
                   10888:                         } elsif ($lock_descriptor eq 'handback') {
                   10889:                             $readonly_files{$file_name} = 'handback';
                   10890:                         } else {
                   10891:                             if (!exists($readonly_files{$file_name})) {
                   10892:                                 $readonly_files{$file_name} = 'locked';
                   10893:                             }
                   10894:                         }
1.745     raeburn  10895:                     }
1.750     banghart 10896:                 } 
1.577     banghart 10897:             }
                   10898:         } 
                   10899:     }
                   10900:     return %readonly_files;
                   10901: }
1.559     banghart 10902: # ------------------------------------------------------------ Unmark as Read Only
                   10903: 
                   10904: sub unmark_as_readonly {
1.629     banghart 10905:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10906:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10907:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10908:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10909:     my $symb_crs = $what;
                   10910:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10911:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10912:     my ($tmp)=keys(%current_permissions);
                   10913:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10914:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10915:     foreach my $file (@readonly_files) {
1.759     albertel 10916: 	my $clean_file = &declutter_portfile($file);
                   10917: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10918: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10919:         my @new_locks;
                   10920:         my @del_keys;
                   10921:         if (ref($current_locks) eq "ARRAY"){
                   10922:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10923:                 my $compare=$locker;
1.749     raeburn  10924:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10925:                     $compare=join('',@{$locker});
1.746     raeburn  10926:                     if ($compare ne $symb_crs) {
                   10927:                         push(@new_locks, $locker);
                   10928:                     }
1.563     banghart 10929:                 }
                   10930:             }
1.650     albertel 10931:             if (scalar(@new_locks) > 0) {
1.563     banghart 10932:                 $current_permissions{$file} = \@new_locks;
                   10933:             } else {
                   10934:                 push(@del_keys, $file);
1.613     albertel 10935:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10936:                 delete($current_permissions{$file});
1.563     banghart 10937:             }
                   10938:         }
1.561     banghart 10939:     }
1.613     albertel 10940:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10941:     return;
                   10942: }
1.512     banghart 10943: 
1.17      www      10944: # ------------------------------------------------------------ Directory lister
                   10945: 
                   10946: sub dirlist {
1.955     raeburn  10947:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10948:     $uri=~s/^\///;
                   10949:     $uri=~s/\/$//;
1.253     stredwic 10950:     my ($udom, $uname);
1.955     raeburn  10951:     if ($getuserdir) {
1.253     stredwic 10952:         $udom = $userdomain;
                   10953:         $uname = $username;
1.955     raeburn  10954:     } else {
                   10955:         (undef,$udom,$uname)=split(/\//,$uri);
                   10956:         if(defined($userdomain)) {
                   10957:             $udom = $userdomain;
                   10958:         }
                   10959:         if(defined($username)) {
                   10960:             $uname = $username;
                   10961:         }
1.253     stredwic 10962:     }
1.955     raeburn  10963:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10964: 
1.955     raeburn  10965:     $dirRoot = $perlvar{'lonDocRoot'};
                   10966:     if (defined($getpropath)) {
                   10967:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10968:         $dirRoot =~ s/\/$//;
1.955     raeburn  10969:     } elsif (defined($getuserdir)) {
                   10970:         my $subdir=$uname.'__';
                   10971:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10972:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10973:                    ."/$udom/$subdir/$uname";
                   10974:     } elsif (defined($alternateRoot)) {
                   10975:         $dirRoot = $alternateRoot;
1.751     banghart 10976:     }
1.253     stredwic 10977: 
                   10978:     if($udom) {
                   10979:         if($uname) {
1.1135    raeburn  10980:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10981:             if ($uhome eq 'no_host') {
                   10982:                 return ([],'no_host');
                   10983:             }
1.955     raeburn  10984:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10985:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10986:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10987:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10988:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10989:             } else {
                   10990:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10991:             }
1.605     matthew  10992:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10993:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10994:                 @listing_results = split(/:/,$listing);
                   10995:             } else {
                   10996:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10997:             }
1.1135    raeburn  10998:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10999:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11000:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11001:                 return ([],$listing);
                   11002:             } else {
                   11003:                 return (\@listing_results);
1.1135    raeburn  11004:             }
1.955     raeburn  11005:         } elsif(!$alternateRoot) {
1.1136    raeburn  11006:             my (%allusers,%listerror);
1.841     albertel 11007: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11008:  	    foreach my $tryserver (keys(%servers)) {
                   11009:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11010:                                   &escape($udom),$tryserver);
                   11011:                 if ($listing eq 'unknown_cmd') {
                   11012: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11013: 				      $udom, $tryserver);
                   11014:                 } else {
                   11015:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11016:                 }
1.841     albertel 11017: 		if ($listing eq 'unknown_cmd') {
                   11018: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11019: 				      $udom, $tryserver);
                   11020: 		    @listing_results = split(/:/,$listing);
                   11021: 		} else {
                   11022: 		    @listing_results =
                   11023: 			map { &unescape($_); } split(/:/,$listing);
                   11024: 		}
1.1136    raeburn  11025:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11026:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11027:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11028:                     $listerror{$tryserver} = $listing;
                   11029:                 } else {
1.841     albertel 11030: 		    foreach my $line (@listing_results) {
                   11031: 			my ($entry) = split(/&/,$line,2);
                   11032: 			$allusers{$entry} = 1;
                   11033: 		    }
                   11034: 		}
1.253     stredwic 11035:             }
1.1136    raeburn  11036:             my @alluserslist=();
1.800     albertel 11037:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11038:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11039:             }
1.1172.2.80  raeburn  11040:             if (!%listerror) {
                   11041:                 # no errors
                   11042:                 return (\@alluserslist);
                   11043:             } elsif (scalar(keys(%servers)) == 1) {
                   11044:                 # one library server, one error
                   11045:                 my ($key) = keys(%listerror);
                   11046:                 return (\@alluserslist, $listerror{$key});
                   11047:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11048:                 # con_lost indicates that we might miss data from at least one
                   11049:                 # library server
                   11050:                 return (\@alluserslist, 'con_lost');
                   11051:             } else {
                   11052:                 # multiple library servers and no con_lost -> data should be
                   11053:                 # complete.
                   11054:                 return (\@alluserslist);
                   11055:             }
                   11056: 
1.253     stredwic 11057:         } else {
1.1136    raeburn  11058:             return ([],'missing username');
1.253     stredwic 11059:         }
1.955     raeburn  11060:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11061:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11062:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11063:         return (\@all_domains);
1.955     raeburn  11064:     } else {
1.1136    raeburn  11065:         return ([],'missing domain');
1.275     stredwic 11066:     }
                   11067: }
                   11068: 
                   11069: # --------------------------------------------- GetFileTimestamp
                   11070: # This function utilizes dirlist and returns the date stamp for
                   11071: # when it was last modified.  It will also return an error of -1
                   11072: # if an error occurs
                   11073: 
                   11074: sub GetFileTimestamp {
1.955     raeburn  11075:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11076:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11077:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11078:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11079:                                     undef,$getuserdir);
                   11080:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11081:         return -1;
                   11082:     }
                   11083:     if (ref($fileref) eq 'ARRAY') {
                   11084:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11085:         # @stats contains first the filename, then the stat output
                   11086:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11087:     } else {
                   11088:         return -1;
1.253     stredwic 11089:     }
1.26      www      11090: }
                   11091: 
1.712     albertel 11092: sub stat_file {
                   11093:     my ($uri) = @_;
1.787     albertel 11094:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11095: 
1.955     raeburn  11096:     my ($udom,$uname,$file);
1.712     albertel 11097:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11098: 	($udom,$uname,$file) =
1.811     albertel 11099: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11100: 	$file = 'userfiles/'.$file;
                   11101:     }
                   11102:     if ($uri =~ m-^/res/-) {
                   11103: 	($udom,$uname) = 
1.807     albertel 11104: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11105: 	$file = $uri;
                   11106:     }
                   11107: 
                   11108:     if (!$udom || !$uname || !$file) {
                   11109: 	# unable to handle the uri
                   11110: 	return ();
                   11111:     }
1.956     raeburn  11112:     my $getpropath;
                   11113:     if ($file =~ /^userfiles\//) {
                   11114:         $getpropath = 1;
                   11115:     }
1.1136    raeburn  11116:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11117:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11118:         return ();
                   11119:     } else {
                   11120:         if (ref($listref) eq 'ARRAY') {
                   11121:             my @stats = split('&',$listref->[0]);
                   11122: 	    shift(@stats); #filename is first
                   11123: 	    return @stats;
                   11124:         }
1.712     albertel 11125:     }
                   11126:     return ();
                   11127: }
                   11128: 
1.26      www      11129: # -------------------------------------------------------- Value of a Condition
                   11130: 
1.713     albertel 11131: # gets the value of a specific preevaluated condition
                   11132: #    stored in the string  $env{user.state.<cid>}
                   11133: # or looks up a condition reference in the bighash and if if hasn't
                   11134: # already been evaluated recurses into docondval to get the value of
                   11135: # the condition, then memoizing it to 
                   11136: #   $env{user.state.<cid>.<condition>}
1.40      www      11137: sub directcondval {
                   11138:     my $number=shift;
1.620     albertel 11139:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11140: 	&Apache::lonuserstate::evalstate();
                   11141:     }
1.713     albertel 11142:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11143: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11144:     } elsif ($number =~ /^_/) {
                   11145: 	my $sub_condition;
                   11146: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11147: 		&GDBM_READER(),0640)) {
                   11148: 	    $sub_condition=$bighash{'conditions'.$number};
                   11149: 	    untie(%bighash);
                   11150: 	}
                   11151: 	my $value = &docondval($sub_condition);
1.949     raeburn  11152: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11153: 	return $value;
                   11154:     }
1.620     albertel 11155:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11156:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11157:     } else {
                   11158:        return 2;
                   11159:     }
                   11160: }
                   11161: 
1.713     albertel 11162: # get the collection of conditions for this resource
1.26      www      11163: sub condval {
                   11164:     my $condidx=shift;
1.54      www      11165:     my $allpathcond='';
1.713     albertel 11166:     foreach my $cond (split(/\|/,$condidx)) {
                   11167: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11168: 	    $allpathcond.=
                   11169: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11170: 	}
1.191     harris41 11171:     }
1.54      www      11172:     $allpathcond=~s/\|$//;
1.713     albertel 11173:     return &docondval($allpathcond);
                   11174: }
                   11175: 
                   11176: #evaluates an expression of conditions
                   11177: sub docondval {
                   11178:     my ($allpathcond) = @_;
                   11179:     my $result=0;
                   11180:     if ($env{'request.course.id'}
                   11181: 	&& defined($allpathcond)) {
                   11182: 	my $operand='|';
                   11183: 	my @stack;
                   11184: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11185: 	    if ($chunk eq '(') {
                   11186: 		push @stack,($operand,$result);
                   11187: 	    } elsif ($chunk eq ')') {
                   11188: 		my $before=pop @stack;
                   11189: 		if (pop @stack eq '&') {
                   11190: 		    $result=$result>$before?$before:$result;
                   11191: 		} else {
                   11192: 		    $result=$result>$before?$result:$before;
                   11193: 		}
                   11194: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11195: 		$operand=$chunk;
                   11196: 	    } else {
                   11197: 		my $new=directcondval($chunk);
                   11198: 		if ($operand eq '&') {
                   11199: 		    $result=$result>$new?$new:$result;
                   11200: 		} else {
                   11201: 		    $result=$result>$new?$result:$new;
                   11202: 		}
                   11203: 	    }
                   11204: 	}
1.26      www      11205:     }
                   11206:     return $result;
1.421     albertel 11207: }
                   11208: 
                   11209: # ---------------------------------------------------- Devalidate courseresdata
                   11210: 
                   11211: sub devalidatecourseresdata {
                   11212:     my ($coursenum,$coursedomain)=@_;
                   11213:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11214:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11215: }
                   11216: 
1.763     www      11217: 
1.200     www      11218: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11219: #
                   11220: #  Parameters:
                   11221: #      $coursenum    - Number of the course.
                   11222: #      $coursedomain - Domain at which the course was created.
                   11223: #  Returns:
                   11224: #     A hash of the course parameters along (I think) with timestamps
                   11225: #     and version info.
1.877     foxr     11226: 
1.624     albertel 11227: sub get_courseresdata {
                   11228:     my ($coursenum,$coursedomain)=@_;
1.200     www      11229:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11230:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11231:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11232:     my %dumpreply;
1.417     albertel 11233:     unless (defined($cached)) {
1.624     albertel 11234: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11235: 	$result=\%dumpreply;
1.251     albertel 11236: 	my ($tmp) = keys(%dumpreply);
                   11237: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11238: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11239: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11240: 	    return $tmp;
1.416     albertel 11241: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11242: 	    $result=undef;
1.599     albertel 11243: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11244: 	}
                   11245:     }
1.624     albertel 11246:     return $result;
                   11247: }
                   11248: 
1.633     albertel 11249: sub devalidateuserresdata {
                   11250:     my ($uname,$udom)=@_;
                   11251:     my $hashid="$udom:$uname";
                   11252:     &devalidate_cache_new('userres',$hashid);
                   11253: }
                   11254: 
1.624     albertel 11255: sub get_userresdata {
                   11256:     my ($uname,$udom)=@_;
                   11257:     #most student don\'t have any data set, check if there is some data
                   11258:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11259: 
                   11260:     my $hashid="$udom:$uname";
                   11261:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11262:     if (!defined($cached)) {
                   11263: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11264: 	$result=\%resourcedata;
                   11265: 	&do_cache_new('userres',$hashid,$result,600);
                   11266:     }
                   11267:     my ($tmp)=keys(%$result);
                   11268:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11269: 	return $result;
                   11270:     }
                   11271:     #error 2 occurs when the .db doesn't exist
                   11272:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11273:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11274: 	    &logthis("<font color=\"blue\">WARNING:".
                   11275: 		     " Trying to get resource data for ".
                   11276: 		     $uname." at ".$udom.": ".
                   11277: 		     $tmp."</font>");
                   11278:         }
1.624     albertel 11279:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11280: 	#&EXT_cache_set($udom,$uname);
                   11281: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11282: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11283:     }
                   11284:     return $tmp;
                   11285: }
1.879     foxr     11286: #----------------------------------------------- resdata - return resource data
                   11287: #  Purpose:
                   11288: #    Return resource data for either users or for a course.
                   11289: #  Parameters:
                   11290: #     $name      - Course/user name.
                   11291: #     $domain    - Name of the domain the user/course is registered on.
                   11292: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11293: #     @which     - Array of names of resources desired.
                   11294: #  Returns:
                   11295: #     The value of the first reasource in @which that is found in the
                   11296: #     resource hash.
                   11297: #  Exceptional Conditions:
                   11298: #     If the $type passed in is not valid (not the string 'course' or 
                   11299: #     'user', an undefined  reference is returned.
                   11300: #     If none of the resources are found, an undef is returned
1.624     albertel 11301: sub resdata {
                   11302:     my ($name,$domain,$type,@which)=@_;
                   11303:     my $result;
                   11304:     if ($type eq 'course') {
                   11305: 	$result=&get_courseresdata($name,$domain);
                   11306:     } elsif ($type eq 'user') {
                   11307: 	$result=&get_userresdata($name,$domain);
                   11308:     }
                   11309:     if (!ref($result)) { return $result; }    
1.251     albertel 11310:     foreach my $item (@which) {
1.927     albertel 11311: 	if (defined($result->{$item->[0]})) {
                   11312: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11313: 	}
1.250     albertel 11314:     }
1.291     albertel 11315:     return undef;
1.200     www      11316: }
                   11317: 
1.1172.2.31  raeburn  11318: sub get_numsuppfiles {
                   11319:     my ($cnum,$cdom,$ignorecache)=@_;
                   11320:     my $hashid=$cnum.':'.$cdom;
                   11321:     my ($suppcount,$cached);
                   11322:     unless ($ignorecache) {
                   11323:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11324:     }
                   11325:     unless (defined($cached)) {
                   11326:         my $chome=&homeserver($cnum,$cdom);
                   11327:         unless ($chome eq 'no_host') {
                   11328:             ($suppcount,my $errors) = (0,0);
                   11329:             my $suppmap = 'supplemental.sequence';
                   11330:             ($suppcount,$errors) =
                   11331:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11332:         }
                   11333:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11334:     }
                   11335:     return $suppcount;
                   11336: }
                   11337: 
1.379     matthew  11338: #
                   11339: # EXT resource caching routines
                   11340: #
                   11341: 
                   11342: sub clear_EXT_cache_status {
1.383     albertel 11343:     &delenv('cache.EXT.');
1.379     matthew  11344: }
                   11345: 
                   11346: sub EXT_cache_status {
                   11347:     my ($target_domain,$target_user) = @_;
1.383     albertel 11348:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11349:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11350:         # We know already the user has no data
                   11351:         return 1;
                   11352:     } else {
                   11353:         return 0;
                   11354:     }
                   11355: }
                   11356: 
                   11357: sub EXT_cache_set {
                   11358:     my ($target_domain,$target_user) = @_;
1.383     albertel 11359:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11360:     #&appenv({$cachename => time});
1.379     matthew  11361: }
                   11362: 
1.28      www      11363: # --------------------------------------------------------- Value of a Variable
1.58      www      11364: sub EXT {
1.715     albertel 11365: 
1.1172.2.28  raeburn  11366:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11367:     unless ($varname) { return ''; }
1.218     albertel 11368:     #get real user name/domain, courseid and symb
                   11369:     my $courseid;
1.359     albertel 11370:     my $publicuser;
1.427     www      11371:     if ($symbparm) {
                   11372: 	$symbparm=&get_symb_from_alias($symbparm);
                   11373:     }
1.218     albertel 11374:     if (!($uname && $udom)) {
1.790     albertel 11375:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11376:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11377:     } else {
1.620     albertel 11378: 	$courseid=$env{'request.course.id'};
1.218     albertel 11379:     }
1.48      www      11380:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11381:     my $rest;
1.320     albertel 11382:     if (defined($therest[0])) {
1.48      www      11383:        $rest=join('.',@therest);
                   11384:     } else {
                   11385:        $rest='';
                   11386:     }
1.320     albertel 11387: 
1.57      www      11388:     my $qualifierrest=$qualifier;
                   11389:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11390:     my $spacequalifierrest=$space;
                   11391:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11392:     if ($realm eq 'user') {
1.48      www      11393: # --------------------------------------------------------------- user.resource
                   11394: 	if ($space eq 'resource') {
1.651     albertel 11395: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11396: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11397: 		 &&
1.744     albertel 11398: 		 ($symbparm eq &symbread()) ) {	
                   11399: 		# if we are in the middle of processing the resource the
                   11400: 		# get the value we are planning on committing
                   11401:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11402:                     return $Apache::lonhomework::results{$qualifierrest};
                   11403:                 } else {
                   11404:                     return $Apache::lonhomework::history{$qualifierrest};
                   11405:                 }
1.335     albertel 11406: 	    } else {
1.359     albertel 11407: 		my %restored;
1.620     albertel 11408: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11409: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11410: 		} else {
                   11411: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11412: 		}
1.335     albertel 11413: 		return $restored{$qualifierrest};
                   11414: 	    }
1.48      www      11415: # ----------------------------------------------------------------- user.access
                   11416:         } elsif ($space eq 'access') {
1.218     albertel 11417: 	    # FIXME - not supporting calls for a specific user
1.48      www      11418:             return &allowed($qualifier,$rest);
                   11419: # ------------------------------------------ user.preferences, user.environment
                   11420:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11421: 	    if (($uname eq $env{'user.name'}) &&
                   11422: 		($udom eq $env{'user.domain'})) {
                   11423: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11424: 	    } else {
1.359     albertel 11425: 		my %returnhash;
                   11426: 		if (!$publicuser) {
                   11427: 		    %returnhash=&userenvironment($udom,$uname,
                   11428: 						 $qualifierrest);
                   11429: 		}
1.218     albertel 11430: 		return $returnhash{$qualifierrest};
                   11431: 	    }
1.48      www      11432: # ----------------------------------------------------------------- user.course
                   11433:         } elsif ($space eq 'course') {
1.218     albertel 11434: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11435:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11436: # ------------------------------------------------------------------- user.role
                   11437:         } elsif ($space eq 'role') {
1.218     albertel 11438: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11439:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11440:             if ($qualifier eq 'value') {
                   11441: 		return $role;
                   11442:             } elsif ($qualifier eq 'extent') {
                   11443:                 return $where;
                   11444:             }
                   11445: # ----------------------------------------------------------------- user.domain
                   11446:         } elsif ($space eq 'domain') {
1.218     albertel 11447:             return $udom;
1.48      www      11448: # ------------------------------------------------------------------- user.name
                   11449:         } elsif ($space eq 'name') {
1.218     albertel 11450:             return $uname;
1.48      www      11451: # ---------------------------------------------------- Any other user namespace
1.29      www      11452:         } else {
1.359     albertel 11453: 	    my %reply;
                   11454: 	    if (!$publicuser) {
                   11455: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11456: 	    }
                   11457: 	    return $reply{$qualifierrest};
1.48      www      11458:         }
1.236     www      11459:     } elsif ($realm eq 'query') {
                   11460: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11461:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11462: 						[$spacequalifierrest]);
1.620     albertel 11463: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11464:    } elsif ($realm eq 'request') {
1.48      www      11465: # ------------------------------------------------------------- request.browser
                   11466:         if ($space eq 'browser') {
1.1145    bisitz   11467:             return $env{'browser.'.$qualifier};
1.57      www      11468: # ------------------------------------------------------------ request.filename
                   11469:         } else {
1.620     albertel 11470:             return $env{'request.'.$spacequalifierrest};
1.29      www      11471:         }
1.28      www      11472:     } elsif ($realm eq 'course') {
1.48      www      11473: # ---------------------------------------------------------- course.description
1.620     albertel 11474:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11475:     } elsif ($realm eq 'resource') {
1.165     www      11476: 
1.620     albertel 11477: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11478: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11479: 	}
1.693     albertel 11480: 
1.1172.2.30  raeburn  11481:         if ($qualifier eq '') {
                   11482: 	    if ($space eq 'title') {
                   11483: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11484: 	        return &gettitle($symbparm);
                   11485: 	    }
1.693     albertel 11486: 	
1.1172.2.30  raeburn  11487: 	    if ($space eq 'map') {
                   11488: 	        my ($map) = &decode_symb($symbparm);
                   11489: 	        return &symbread($map);
                   11490: 	    }
                   11491:             if ($space eq 'maptitle') {
                   11492:                 my ($map) = &decode_symb($symbparm);
                   11493:                 return &gettitle($map);
                   11494:             }
                   11495: 	    if ($space eq 'filename') {
                   11496: 	        if ($symbparm) {
                   11497: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11498: 	        }
                   11499: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11500: 	    }
1.1172.2.30  raeburn  11501: 
                   11502:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11503:                 if ($space eq 'visibleparts') {
                   11504:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11505:                     my $item;
                   11506:                     if (ref($navmap)) {
                   11507:                         my $res = $navmap->getBySymb($symbparm);
                   11508:                         my $parts = $res->parts();
                   11509:                         if (ref($parts) eq 'ARRAY') {
                   11510:                             $item = join(',',@{$parts});
                   11511:                         }
                   11512:                         undef($navmap);
                   11513:                     }
                   11514:                     return $item;
                   11515:                 }
                   11516:             }
                   11517:         }
1.693     albertel 11518: 
                   11519: 	my ($section, $group, @groups);
1.593     albertel 11520: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11521:         if (($courseid eq '') && ($cid)) {
                   11522:             $courseid = $cid;
                   11523:         }
                   11524: 	if (($symbparm && $courseid) && 
                   11525: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11526: 
1.218     albertel 11527: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11528: 
1.60      www      11529: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11530: 	    my $symbp=$symbparm;
1.735     albertel 11531: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11532: 
                   11533: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11534: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11535: 
1.620     albertel 11536: 	    if (($env{'user.name'} eq $uname) &&
                   11537: 		($env{'user.domain'} eq $udom)) {
                   11538: 		$section=$env{'request.course.sec'};
1.733     raeburn  11539:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11540:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11541: 	    } else {
1.539     albertel 11542: 		if (! defined($usection)) {
1.551     albertel 11543: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11544: 		} else {
                   11545: 		    $section = $usection;
                   11546: 		}
1.733     raeburn  11547:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11548: 	    }
                   11549: 
                   11550: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11551: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11552: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11553: 
1.593     albertel 11554: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11555: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11556: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11557: 
1.60      www      11558: # ----------------------------------------------------------- first, check user
1.624     albertel 11559: 
                   11560: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11561: 				       ([$courselevelr,'resource'],
                   11562: 					[$courselevelm,'map'     ],
                   11563: 					[$courselevel, 'course'  ]));
1.931     albertel 11564: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11565: 
1.594     albertel 11566: # ------------------------------------------------ second, check some of course
1.684     raeburn  11567:             my $coursereply;
1.691     raeburn  11568:             if (@groups > 0) {
                   11569:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11570:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11571:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11572:             }
1.96      www      11573: 
1.684     raeburn  11574: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11575: 				  $env{'course.'.$courseid.'.domain'},
                   11576: 				  'course',
                   11577: 				  ([$seclevelr,   'resource'],
                   11578: 				   [$seclevelm,   'map'     ],
                   11579: 				   [$seclevel,    'course'  ],
                   11580: 				   [$courselevelr,'resource']));
                   11581: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11582: 
1.60      www      11583: # ------------------------------------------------------ third, check map parms
1.218     albertel 11584: 	    my %parmhash=();
                   11585: 	    my $thisparm='';
                   11586: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11587: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11588: 		    &GDBM_READER(),0640)) {
1.218     albertel 11589: 		$thisparm=$parmhash{$symbparm};
                   11590: 		untie(%parmhash);
                   11591: 	    }
1.927     albertel 11592: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11593: 	}
1.594     albertel 11594: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11595: 
1.218     albertel 11596: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11597: 	my $filename;
                   11598: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11599: 	if ($symbparm) {
1.409     www      11600: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11601: 	} else {
1.620     albertel 11602: 	    $filename=$env{'request.filename'};
1.282     albertel 11603: 	}
                   11604: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11605: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11606: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11607: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11608: 
1.927     albertel 11609: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11610: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11611: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11612: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11613: 				     $env{'course.'.$courseid.'.domain'},
                   11614: 				     'course',
1.927     albertel 11615: 				     ([$courselevelm,'map'   ],
                   11616: 				      [$courselevel, 'course']));
                   11617: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11618: 	}
1.145     www      11619: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11620: 	unless ($space eq '0') {
1.336     albertel 11621: 	    my @parts=split(/_/,$space);
                   11622: 	    my $id=pop(@parts);
                   11623: 	    my $part=join('_',@parts);
                   11624: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11625: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11626: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11627: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11628: 	}
1.395     albertel 11629: 	if ($recurse) { return undef; }
                   11630: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11631: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11632: # ---------------------------------------------------- Any other user namespace
                   11633:     } elsif ($realm eq 'environment') {
                   11634: # ----------------------------------------------------------------- environment
1.620     albertel 11635: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11636: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11637: 	} else {
1.770     albertel 11638: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11639: 		return '';
                   11640: 	    }
1.219     albertel 11641: 	    my %returnhash=&userenvironment($udom,$uname,
                   11642: 					    $spacequalifierrest);
                   11643: 	    return $returnhash{$spacequalifierrest};
                   11644: 	}
1.28      www      11645:     } elsif ($realm eq 'system') {
1.48      www      11646: # ----------------------------------------------------------------- system.time
                   11647: 	if ($space eq 'time') {
                   11648: 	    return time;
                   11649:         }
1.696     albertel 11650:     } elsif ($realm eq 'server') {
                   11651: # ----------------------------------------------------------------- system.time
                   11652: 	if ($space eq 'name') {
                   11653: 	    return $ENV{'SERVER_NAME'};
                   11654:         }
1.28      www      11655:     }
1.48      www      11656:     return '';
1.61      www      11657: }
                   11658: 
1.927     albertel 11659: sub get_reply {
                   11660:     my ($reply_value) = @_;
1.940     raeburn  11661:     if (ref($reply_value) eq 'ARRAY') {
                   11662:         if (wantarray) {
                   11663: 	    return @$reply_value;
                   11664:         }
                   11665:         return $reply_value->[0];
                   11666:     } else {
                   11667:         return $reply_value;
1.927     albertel 11668:     }
                   11669: }
                   11670: 
1.691     raeburn  11671: sub check_group_parms {
                   11672:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11673:     my @groupitems = ();
                   11674:     my $resultitem;
1.927     albertel 11675:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11676:     foreach my $group (@{$groups}) {
                   11677:         foreach my $level (@levels) {
1.927     albertel 11678:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11679:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11680:         }
                   11681:     }
                   11682:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11683:                             $env{'course.'.$courseid.'.domain'},
                   11684:                                      'course',@groupitems);
                   11685:     return $coursereply;
                   11686: }
                   11687: 
                   11688: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11689:     my ($courseid,@groups) = @_;
                   11690:     @groups = sort(@groups);
1.691     raeburn  11691:     return @groups;
                   11692: }
                   11693: 
1.395     albertel 11694: sub packages_tab_default {
                   11695:     my ($uri,$varname)=@_;
                   11696:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11697: 
                   11698:     my (@extension,@specifics,$do_default);
                   11699:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11700: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11701: 	if ($pack_type eq 'default') {
                   11702: 	    $do_default=1;
                   11703: 	} elsif ($pack_type eq 'extension') {
                   11704: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11705: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11706: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11707: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11708: 	}
                   11709:     }
                   11710:     # first look for a package that matches the requested part id
                   11711:     foreach my $package (@specifics) {
                   11712: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11713: 	next if ($pack_part ne $part);
                   11714: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11715: 	    return $packagetab{"$pack_type&$name&default"};
                   11716: 	}
                   11717:     }
                   11718:     # look for any possible matching non extension_ package
                   11719:     foreach my $package (@specifics) {
                   11720: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11721: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11722: 	    return $packagetab{"$pack_type&$name&default"};
                   11723: 	}
1.585     albertel 11724: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11725: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11726: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11727: 	}
                   11728:     }
1.738     albertel 11729:     # look for any posible extension_ match
                   11730:     foreach my $package (@extension) {
                   11731: 	my ($package,$pack_type)=@{$package};
                   11732: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11733: 	    return $packagetab{"$pack_type&$name&default"};
                   11734: 	}
                   11735: 	if (defined($packagetab{$package."&$name&default"})) {
                   11736: 	    return $packagetab{$package."&$name&default"};
                   11737: 	}
                   11738:     }
                   11739:     # look for a global default setting
                   11740:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11741: 	return $packagetab{"default&$name&default"};
                   11742:     }
1.395     albertel 11743:     return undef;
                   11744: }
                   11745: 
1.334     albertel 11746: sub add_prefix_and_part {
                   11747:     my ($prefix,$part)=@_;
                   11748:     my $keyroot;
                   11749:     if (defined($prefix) && $prefix !~ /^__/) {
                   11750: 	# prefix that has a part already
                   11751: 	$keyroot=$prefix;
                   11752:     } elsif (defined($prefix)) {
                   11753: 	# prefix that is missing a part
                   11754: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11755:     } else {
                   11756: 	# no prefix at all
                   11757: 	if (defined($part)) { $keyroot='_'.$part; }
                   11758:     }
                   11759:     return $keyroot;
                   11760: }
                   11761: 
1.71      www      11762: # ---------------------------------------------------------------- Get metadata
                   11763: 
1.599     albertel 11764: my %metaentry;
1.1070    www      11765: my %importedpartids;
1.1172.2.99  raeburn  11766: my %importedrespids;
1.71      www      11767: sub metadata {
1.176     www      11768:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11769:     $uri=&declutter($uri);
1.288     albertel 11770:     # if it is a non metadata possible uri return quickly
1.529     albertel 11771:     if (($uri eq '') || 
                   11772: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11773: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11774:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11775: 	return undef;
                   11776:     }
1.1172.2.49  raeburn  11777:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11778: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11779: 	return undef;
1.288     albertel 11780:     }
1.73      www      11781:     my $filename=$uri;
                   11782:     $uri=~s/\.meta$//;
1.172     www      11783: #
                   11784: # Is the metadata already cached?
1.177     www      11785: # Look at timestamp of caching
1.172     www      11786: # Everything is cached by the main uri, libraries are never directly cached
                   11787: #
1.428     albertel 11788:     if (!defined($liburi)) {
1.599     albertel 11789: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11790: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11791:     }
                   11792:     {
1.1069    www      11793: # Imported parts would go here
1.1172.2.99  raeburn  11794:         my @origfiletagids=();
1.1069    www      11795:         my $importedparts=0;
1.1172.2.99  raeburn  11796: 
                   11797: # Imported responseids would go here
                   11798:         my $importedresponses=0;
1.172     www      11799: #
                   11800: # Is this a recursive call for a library?
                   11801: #
1.599     albertel 11802: #	if (! exists($metacache{$uri})) {
                   11803: #	    $metacache{$uri}={};
                   11804: #	}
1.924     albertel 11805: 	my $cachetime = 60*60;
1.171     www      11806:         if ($liburi) {
                   11807: 	    $liburi=&declutter($liburi);
                   11808:             $filename=$liburi;
1.401     bowersj2 11809:         } else {
1.599     albertel 11810: 	    &devalidate_cache_new('meta',$uri);
                   11811: 	    undef(%metaentry);
1.401     bowersj2 11812: 	}
1.140     www      11813:         my %metathesekeys=();
1.73      www      11814:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11815: 	my $metastring;
1.1140    www      11816: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11817: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11818: 	    $metastring = 
1.929     albertel 11819: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11820: 					  ('grade_target' => 'meta'));
                   11821: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11822: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11823:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11824: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11825: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11826: 	    $metastring=&getfile($file);
1.489     albertel 11827: 	}
1.208     albertel 11828:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11829:         my $token;
1.140     www      11830:         undef %metathesekeys;
1.71      www      11831:         while ($token=$parser->get_token) {
1.339     albertel 11832: 	    if ($token->[0] eq 'S') {
                   11833: 		if (defined($token->[2]->{'package'})) {
1.172     www      11834: #
                   11835: # This is a package - get package info
                   11836: #
1.339     albertel 11837: 		    my $package=$token->[2]->{'package'};
                   11838: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11839: 		    if (defined($token->[2]->{'id'})) { 
                   11840: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11841: 		    }
1.599     albertel 11842: 		    if ($metaentry{':packages'}) {
                   11843: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11844: 		    } else {
1.599     albertel 11845: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11846: 		    }
1.736     albertel 11847: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11848: 			my $part=$keyroot;
                   11849: 			$part=~s/^\_//;
1.736     albertel 11850: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11851: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11852: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11853: 			    # ignore package.tab specified default values
                   11854:                             # here &package_tab_default() will fetch those
                   11855: 			    if ($subp eq 'default') { next; }
1.736     albertel 11856: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11857: 			    my $unikey;
                   11858: 			    if ($pack =~ /_0$/) {
                   11859: 				$unikey='parameter_0_'.$name;
                   11860: 				$part=0;
                   11861: 			    } else {
                   11862: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11863: 			    }
1.339     albertel 11864: 			    if ($subp eq 'display') {
                   11865: 				$value.=' [Part: '.$part.']';
                   11866: 			    }
1.599     albertel 11867: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11868: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11869: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11870: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11871: 			    }
1.599     albertel 11872: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11873: 				$metaentry{':'.$unikey}=
                   11874: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11875: 			    }
1.339     albertel 11876: 			}
                   11877: 		    }
                   11878: 		} else {
1.172     www      11879: #
                   11880: # This is not a package - some other kind of start tag
1.339     albertel 11881: #
                   11882: 		    my $entry=$token->[1];
1.1068    www      11883: 		    my $unikey='';
1.175     www      11884: 
1.339     albertel 11885: 		    if ($entry eq 'import') {
1.175     www      11886: #
                   11887: # Importing a library here
1.339     albertel 11888: #
1.1067    www      11889:                         my $location=$parser->get_text('/import');
                   11890:                         my $dir=$filename;
                   11891:                         $dir=~s|[^/]*$||;
                   11892:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11893: 
                   11894:                         my $importid=$token->[2]->{'id'};
1.1068    www      11895:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11896: #
                   11897: # Check metadata for imported file to
                   11898: # see if it contained response items
                   11899: #
                   11900:                         my %currmetaentry = %metaentry;
                   11901:                         my $libresponseorder = &metadata($location,'responseorder');
                   11902:                         my $origfile;
                   11903:                         if ($libresponseorder ne '') {
                   11904:                             if ($#origfiletagids<0) {
                   11905:                                 undef(%importedrespids);
                   11906:                                 undef(%importedpartids);
                   11907:                             }
                   11908:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11909:                             if (@{$importedrespids{$importid}} > 0) {
                   11910:                                 $importedresponses = 1;
                   11911: # We need to get the original file and the imported file to get the response order correct
                   11912: # Load and inspect original file
                   11913:                                 if ($#origfiletagids<0) {
                   11914:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11915:                                     $origfile=&getfile($origfilelocation);
                   11916:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11917:                                 }
                   11918:                             }
                   11919:                         }
                   11920: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11921: # hash populated for imported library file
                   11922:                         %metaentry = %currmetaentry;
                   11923:                         undef(%currmetaentry);
1.1068    www      11924:                         if ($importmode eq 'problem') {
1.1069    www      11925: # Import as problem/response
1.1068    www      11926:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11927:                         } elsif ($importmode eq 'part') {
                   11928: # Import as part(s)
1.1069    www      11929:                            $importedparts=1;
                   11930: # We need to get the original file and the imported file to get the part order correct
                   11931: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11932: # Load and inspect original file if we didn't do that already
                   11933:                            if ($#origfiletagids<0) {
                   11934:                                undef(%importedrespids);
                   11935:                                undef(%importedpartids);
                   11936:                                if ($origfile eq '') {
                   11937:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11938:                                    $origfile=&getfile($origfilelocation);
                   11939:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11940:                                }
1.1070    www      11941:                            }
                   11942: 
1.1069    www      11943: # Load and inspect imported file
                   11944:                            my $impfile=&getfile($location);
                   11945:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11946:                            if ($#impfilepartids>=0) {
                   11947: # This problem had parts
1.1070    www      11948:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11949:                            } else {
                   11950: # Importing by turning a single problem into a problem part
                   11951: # It gets the import-tags ID as part-ID
                   11952:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11953:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11954:                            }
1.1068    www      11955:                         } else {
                   11956: # Normal import
                   11957:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11958:                            if (defined($token->[2]->{'id'})) {
                   11959:                               $unikey.='_'.$token->[2]->{'id'};
                   11960:                            }
1.1067    www      11961:                         }
                   11962: 
1.339     albertel 11963: 			if ($depthcount<20) {
1.736     albertel 11964: 			    my $metadata = 
                   11965: 				&metadata($uri,'keys', $location,$unikey,
                   11966: 					  $depthcount+1);
                   11967: 			    foreach my $meta (split(',',$metadata)) {
                   11968: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11969: 				$metathesekeys{$meta}=1;
1.339     albertel 11970: 			    }
1.1068    www      11971: 			
                   11972:                         }
1.1067    www      11973: 		    } else {
                   11974: #
                   11975: # Not importing, some other kind of non-package, non-library start tag
                   11976: # 
                   11977:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11978:                         if (defined($token->[2]->{'id'})) {
                   11979:                             $unikey.='_'.$token->[2]->{'id'};
                   11980:                         }
1.339     albertel 11981: 			if (defined($token->[2]->{'name'})) { 
                   11982: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11983: 			}
                   11984: 			$metathesekeys{$unikey}=1;
1.736     albertel 11985: 			foreach my $param (@{$token->[3]}) {
                   11986: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11987: 				$token->[2]->{$param};
1.339     albertel 11988: 			}
                   11989: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11990: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11991: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11992: 		 # only ws inside the tag, and not in default, so use default
                   11993: 		 # as value
1.599     albertel 11994: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11995: 			} elsif ( $internaltext =~ /\S/ ) {
                   11996: 		  # something interesting inside the tag
                   11997: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11998: 			} else {
1.908     albertel 11999: 		  # no interesting values, don't set a default
1.339     albertel 12000: 			}
1.172     www      12001: # end of not-a-package not-a-library import
1.339     albertel 12002: 		    }
1.172     www      12003: # end of not-a-package start tag
1.339     albertel 12004: 		}
1.172     www      12005: # the next is the end of "start tag"
1.339     albertel 12006: 	    }
                   12007: 	}
1.483     albertel 12008: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12009: 	$extension = lc($extension);
                   12010: 	if ($extension eq 'htm') { $extension='html'; }
                   12011: 
1.737     albertel 12012: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12013: 	    #no specific packages #how's our extension
                   12014: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12015: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12016: 					 \%metathesekeys);
                   12017: 	}
1.883     albertel 12018: 
                   12019: 	if (!exists($metaentry{':packages'})
                   12020: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12021: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12022: 		#no specific packages well let's get default then
                   12023: 		if ($key!~/^default&/) { next; }
1.488     albertel 12024: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12025: 					     \%metathesekeys);
                   12026: 	    }
                   12027: 	}
1.338     www      12028: # are there custom rights to evaluate
1.599     albertel 12029: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12030: 
1.338     www      12031:     #
                   12032:     # Importing a rights file here
1.339     albertel 12033:     #
                   12034: 	    unless ($depthcount) {
1.599     albertel 12035: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12036: 		my $dir=$filename;
                   12037: 		$dir=~s|[^/]*$||;
                   12038: 		$location=&filelocation($dir,$location);
1.736     albertel 12039: 		my $rights_metadata =
                   12040: 		    &metadata($uri,'keys',$location,'_rights',
                   12041: 			      $depthcount+1);
                   12042: 		foreach my $rights (split(',',$rights_metadata)) {
                   12043: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12044: 		    $metathesekeys{$rights}=1;
1.339     albertel 12045: 		}
                   12046: 	    }
                   12047: 	}
1.737     albertel 12048: 	# uniqifiy package listing
                   12049: 	my %seen;
                   12050: 	my @uniq_packages =
                   12051: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12052: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12053: 
1.1172.2.99  raeburn  12054:         if (($importedresponses) || ($importedparts)) {
                   12055:             if ($importedparts) {
1.1070    www      12056: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12057:                 $metaentry{':partorder'}='';
                   12058:                 $metathesekeys{'partorder'}=1;
                   12059:             }
                   12060:             if ($importedresponses) {
                   12061: # We had imported responses and need to rebuild responseorder
                   12062:                 $metaentry{':responseorder'}='';
                   12063:                 $metathesekeys{'responseorder'}=1;
                   12064:             }
                   12065:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12066:                 my $origid = $origfiletagids[$index+1];
                   12067:                 if ($origfiletagids[$index] eq 'part') {
                   12068: # Original part, part of the problem
                   12069:                     if ($importedparts) {
                   12070:                         $metaentry{':partorder'}.=','.$origid;
                   12071:                     }
                   12072:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12073:                     if ($importedparts) {
                   12074: # We have imported parts at this position
                   12075:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12076:                     }
                   12077:                     if ($importedresponses) {
                   12078: # We have imported responses at this position
                   12079:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12080:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12081:                         }
                   12082:                     }
                   12083:                 } else {
                   12084: # Original response item, part of the problem
                   12085:                     if ($importedresponses) {
                   12086:                         $metaentry{':responseorder'}.=','.$origid;
                   12087:                     }
                   12088:                 }
                   12089:             }
                   12090:             if ($importedparts) {
                   12091:                 $metaentry{':partorder'}=~s/^\,//;
                   12092:             }
                   12093:             if ($importedresponses) {
                   12094:                 $metaentry{':responseorder'}=~s/^\,//;
                   12095:             }
1.1070    www      12096:         }
                   12097: 
1.737     albertel 12098: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12099: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12100: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12101: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12102: # this is the end of "was not already recently cached
1.71      www      12103:     }
1.599     albertel 12104:     return $metaentry{':'.$what};
1.261     albertel 12105: }
                   12106: 
1.488     albertel 12107: sub metadata_create_package_def {
1.483     albertel 12108:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12109:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12110:     if ($subp eq 'default') { next; }
                   12111:     
1.599     albertel 12112:     if (defined($metaentry{':packages'})) {
                   12113: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12114:     } else {
1.599     albertel 12115: 	$metaentry{':packages'}=$package;
1.483     albertel 12116:     }
                   12117:     my $value=$packagetab{$key};
                   12118:     my $unikey;
                   12119:     $unikey='parameter_0_'.$name;
1.599     albertel 12120:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12121:     $$metathesekeys{$unikey}=1;
1.599     albertel 12122:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12123: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12124:     }
1.599     albertel 12125:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12126: 	$metaentry{':'.$unikey}=
                   12127: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12128:     }
                   12129: }
                   12130: 
1.261     albertel 12131: sub metadata_generate_part0 {
                   12132:     my ($metadata,$metacache,$uri) = @_;
                   12133:     my %allnames;
1.737     albertel 12134:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12135: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12136: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12137: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12138: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12139: 	    $allnames{$name}=$part;
                   12140: 	  }
                   12141: 	}
                   12142:     }
                   12143:     foreach my $name (keys(%allnames)) {
                   12144:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12145:       my $key=":parameter_0_$name";
1.261     albertel 12146:       $$metacache{"$key.part"}='0';
                   12147:       $$metacache{"$key.name"}=$name;
1.428     albertel 12148:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12149: 					   $allnames{$name}.'_'.$name.
                   12150: 					   '.type'};
1.428     albertel 12151:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12152: 			     '.display'};
1.644     www      12153:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12154:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12155:       $$metacache{"$key.display"}=$olddis;
                   12156:     }
1.71      www      12157: }
                   12158: 
1.764     albertel 12159: # ------------------------------------------------------ Devalidate title cache
                   12160: 
                   12161: sub devalidate_title_cache {
                   12162:     my ($url)=@_;
                   12163:     if (!$env{'request.course.id'}) { return; }
                   12164:     my $symb=&symbread($url);
                   12165:     if (!$symb) { return; }
                   12166:     my $key=$env{'request.course.id'}."\0".$symb;
                   12167:     &devalidate_cache_new('title',$key);
                   12168: }
                   12169: 
1.1014    droeschl 12170: # ------------------------------------------------- Get the title of a course
                   12171: 
                   12172: sub current_course_title {
                   12173:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12174: }
1.301     www      12175: # ------------------------------------------------- Get the title of a resource
                   12176: 
                   12177: sub gettitle {
                   12178:     my $urlsymb=shift;
                   12179:     my $symb=&symbread($urlsymb);
1.534     albertel 12180:     if ($symb) {
1.620     albertel 12181: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12182: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12183: 	if (defined($cached)) { 
                   12184: 	    return $result;
                   12185: 	}
1.534     albertel 12186: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12187: 	my $title='';
1.907     albertel 12188: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12189: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12190: 	} else {
                   12191: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12192: 		    &GDBM_READER(),0640)) {
                   12193: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12194: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12195: 		untie(%bighash);
                   12196: 	    }
1.534     albertel 12197: 	}
                   12198: 	$title=~s/\&colon\;/\:/gs;
                   12199: 	if ($title) {
1.1159    www      12200: # Remember both $symb and $title for dynamic metadata
                   12201:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12202:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12203: # Cache this title and then return it
1.599     albertel 12204: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12205: 	}
                   12206: 	$urlsymb=$url;
                   12207:     }
                   12208:     my $title=&metadata($urlsymb,'title');
                   12209:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12210:     return $title;
1.301     www      12211: }
1.613     albertel 12212: 
1.614     albertel 12213: sub get_slot {
                   12214:     my ($which,$cnum,$cdom)=@_;
                   12215:     if (!$cnum || !$cdom) {
1.790     albertel 12216: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12217: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12218: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12219:     }
1.703     albertel 12220:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12221:     my %slotinfo;
                   12222:     if (exists($remembered{$key})) {
                   12223: 	$slotinfo{$which} = $remembered{$key};
                   12224:     } else {
                   12225: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12226: 	&Apache::lonhomework::showhash(%slotinfo);
                   12227: 	my ($tmp)=keys(%slotinfo);
                   12228: 	if ($tmp=~/^error:/) { return (); }
                   12229: 	$remembered{$key} = $slotinfo{$which};
                   12230:     }
1.616     albertel 12231:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12232: 	return %{$slotinfo{$which}};
                   12233:     }
                   12234:     return $slotinfo{$which};
1.614     albertel 12235: }
1.1150    raeburn  12236: 
                   12237: sub get_reservable_slots {
                   12238:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12239:     my $now = time;
                   12240:     my $reservable_info;
                   12241:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12242:     if (exists($remembered{$key})) {
                   12243:         $reservable_info = $remembered{$key};
                   12244:     } else {
                   12245:         my %resv;
                   12246:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12247:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12248:         $reservable_info = \%resv;
                   12249:         $remembered{$key} = $reservable_info;
                   12250:     }
                   12251:     return $reservable_info;
                   12252: }
                   12253: 
                   12254: sub get_course_slots {
                   12255:     my ($cnum,$cdom) = @_;
                   12256:     my $hashid=$cnum.':'.$cdom;
                   12257:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12258:     if (defined($cached)) {
                   12259:         if (ref($result) eq 'HASH') {
                   12260:             return %{$result};
                   12261:         }
                   12262:     } else {
                   12263:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12264:         my ($tmp) = keys(%slots);
                   12265:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12266:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12267:             return %slots;
                   12268:         }
                   12269:     }
                   12270:     return;
                   12271: }
                   12272: 
                   12273: sub devalidate_slots_cache {
                   12274:     my ($cnum,$cdom)=@_;
                   12275:     my $hashid=$cnum.':'.$cdom;
                   12276:     &devalidate_cache_new('allslots',$hashid);
                   12277: }
                   12278: 
1.1172.2.8  raeburn  12279: sub get_coursechange {
                   12280:     my ($cdom,$cnum) = @_;
                   12281:     if ($cdom eq '' || $cnum eq '') {
                   12282:         return unless ($env{'request.course.id'});
                   12283:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12284:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12285:     }
                   12286:     my $hashid=$cdom.'_'.$cnum;
                   12287:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12288:     if ((defined($cached)) && ($change ne '')) {
                   12289:         return $change;
                   12290:     } else {
                   12291:         my %crshash;
                   12292:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12293:         if ($crshash{'internal.contentchange'} eq '') {
                   12294:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12295:             if ($change eq '') {
                   12296:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12297:                 $change = $crshash{'internal.created'};
                   12298:             }
                   12299:         } else {
                   12300:             $change = $crshash{'internal.contentchange'};
                   12301:         }
                   12302:         my $cachetime = 600;
                   12303:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12304:     }
                   12305:     return $change;
                   12306: }
                   12307: 
                   12308: sub devalidate_coursechange_cache {
                   12309:     my ($cnum,$cdom)=@_;
                   12310:     my $hashid=$cnum.':'.$cdom;
                   12311:     &devalidate_cache_new('crschange',$hashid);
                   12312: }
                   12313: 
1.31      www      12314: # ------------------------------------------------- Update symbolic store links
                   12315: 
                   12316: sub symblist {
                   12317:     my ($mapname,%newhash)=@_;
1.438     www      12318:     $mapname=&deversion(&declutter($mapname));
1.31      www      12319:     my %hash;
1.620     albertel 12320:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12321:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12322:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12323: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12324: 		next if ($url eq 'last_known'
                   12325: 			 && $env{'form.no_update_last_known'});
                   12326: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12327: 						    $newhash{$url}->[1],
                   12328: 						    $newhash{$url}->[0]);
1.191     harris41 12329:             }
1.31      www      12330:             if (untie(%hash)) {
                   12331: 		return 'ok';
                   12332:             }
                   12333:         }
                   12334:     }
                   12335:     return 'error';
1.212     www      12336: }
                   12337: 
                   12338: # --------------------------------------------------------------- Verify a symb
                   12339: 
                   12340: sub symbverify {
1.1172.2.11  raeburn  12341:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12342:     my $thisfn=$thisurl;
1.439     www      12343:     $thisfn=&declutter($thisfn);
1.215     www      12344: # direct jump to resource in page or to a sequence - will construct own symbs
                   12345:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12346: # check URL part
1.409     www      12347:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12348: 
1.431     www      12349:     unless ($url eq $thisfn) { return 0; }
1.213     www      12350: 
1.216     www      12351:     $symb=&symbclean($symb);
1.510     www      12352:     $thisurl=&deversion($thisurl);
1.439     www      12353:     $thisfn=&deversion($thisfn);
1.213     www      12354: 
                   12355:     my %bighash;
                   12356:     my $okay=0;
1.431     www      12357: 
1.620     albertel 12358:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12359:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12360:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12361:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12362:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12363:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12364:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12365:             }
                   12366:         }
                   12367:         my $ids;
1.1172.2.122  raeburn  12368:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12369:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12370:         } else {
                   12371:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12372:         }
1.1102    raeburn  12373:         unless ($ids) {
1.1172.2.13  raeburn  12374:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12375:             $ids=$bighash{$idkey};
1.216     www      12376:         }
                   12377:         if ($ids) {
                   12378: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12379:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12380:                 $symb =~ s/\?.+$//;
                   12381:             }
1.800     albertel 12382: 	    foreach my $id (split(/\,/,$ids)) {
                   12383: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12384:                if (
                   12385:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12386:    eq $symb) {
1.1172.2.11  raeburn  12387:                    if (ref($encstate)) {
                   12388:                        $$encstate = $bighash{'encrypted_'.$id};
                   12389:                    }
1.1172.2.13  raeburn  12390:                    if (($env{'request.role.adv'}) ||
                   12391:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12392:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12393:                        $okay=1;
                   12394:                        last;
                   12395:                    }
                   12396:                }
                   12397:            }
1.216     www      12398:         }
1.213     www      12399: 	untie(%bighash);
                   12400:     }
                   12401:     return $okay;
1.31      www      12402: }
                   12403: 
1.210     www      12404: # --------------------------------------------------------------- Clean-up symb
                   12405: 
                   12406: sub symbclean {
                   12407:     my $symb=shift;
1.568     albertel 12408:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12409: # remove version from map
                   12410:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12411: 
1.210     www      12412: # remove version from URL
                   12413:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12414: 
1.507     www      12415: # remove wrapper
                   12416: 
1.510     www      12417:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12418:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12419:     return $symb;
1.409     www      12420: }
                   12421: 
                   12422: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12423: 
                   12424: sub encode_symb {
                   12425:     my ($map,$resid,$url)=@_;
                   12426:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12427: }
1.409     www      12428: 
                   12429: sub decode_symb {
1.568     albertel 12430:     my $symb=shift;
                   12431:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12432:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12433:     return (&fixversion($map),$resid,&fixversion($url));
                   12434: }
                   12435: 
                   12436: sub fixversion {
                   12437:     my $fn=shift;
1.609     banghart 12438:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12439:     my %bighash;
                   12440:     my $uri=&clutter($fn);
1.620     albertel 12441:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12442: # is this cached?
1.599     albertel 12443:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12444:     if (defined($cached)) { return $result; }
                   12445: # unfortunately not cached, or expired
1.620     albertel 12446:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12447: 	    &GDBM_READER(),0640)) {
                   12448:  	if ($bighash{'version_'.$uri}) {
                   12449:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12450:  	    unless (($version eq 'mostrecent') || 
                   12451: 		    ($version==&getversion($uri))) {
1.440     www      12452:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12453:  	    }
                   12454:  	}
                   12455:  	untie %bighash;
1.413     www      12456:     }
1.599     albertel 12457:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12458: }
                   12459: 
                   12460: sub deversion {
                   12461:     my $url=shift;
                   12462:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12463:     return $url;
1.210     www      12464: }
                   12465: 
1.31      www      12466: # ------------------------------------------------------ Return symb list entry
                   12467: 
                   12468: sub symbread {
1.1172.2.126  raeburn  12469:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12470:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12471:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12472:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12473:         unless (ref($possibles) eq 'HASH') {
                   12474:             if ($ignorecachednull) {
                   12475:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12476:             } else {
                   12477:                 return $env{$cache_str};
                   12478:             }
1.1172.2.66  raeburn  12479:         }
                   12480:     }
1.242     www      12481: # no filename provided? try from environment
1.1172.2.54  raeburn  12482:     unless ($thisfn) {
1.620     albertel 12483:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12484:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12485:         }
                   12486:         $thisfn=$env{'request.filename'};
1.44      www      12487:     }
1.569     albertel 12488:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12489: # is that filename actually a symb? Verify, clean, and return
                   12490:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12491: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12492: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12493: 	}
1.242     www      12494:     }
1.44      www      12495:     $thisfn=declutter($thisfn);
1.31      www      12496:     my %hash;
1.37      www      12497:     my %bighash;
                   12498:     my $syval='';
1.620     albertel 12499:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12500:         my $targetfn = $thisfn;
1.609     banghart 12501:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12502:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12503:         }
1.687     albertel 12504: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12505: 	    $targetfn=$1;
                   12506: 	}
1.1172.2.128  raeburn  12507:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12508:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12509:                           &GDBM_READER(),0640)) {
                   12510: 	        $syval=$hash{$targetfn};
                   12511:                 untie(%hash);
                   12512:             }
1.1172.2.128  raeburn  12513:             if ($syval && $checkforblock) {
                   12514:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12515:                 if (@blockers) {
                   12516:                     $syval='';
                   12517:                 }
                   12518:             }
1.37      www      12519:         }
                   12520: # ---------------------------------------------------------- There was an entry
                   12521:         if ($syval) {
1.601     albertel 12522: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12523: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12524: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12525: 		    #return $env{$cache_str}='';
1.601     albertel 12526: 		#}    
                   12527: 		#$syval.=$1;
                   12528: 	    #}
1.37      www      12529:         } else {
                   12530: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12531:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12532:                             &GDBM_READER(),0640)) {
1.37      www      12533: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12534:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12535:               unless ($ids) { 
                   12536:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12537:               }
                   12538:               unless ($ids) {
                   12539: # alias?
                   12540: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12541:               }
1.37      www      12542:               if ($ids) {
                   12543: # ------------------------------------------------------------------- Has ID(s)
                   12544:                  my @possibilities=split(/\,/,$ids);
1.39      www      12545:                  if ($#possibilities==0) {
                   12546: # ----------------------------------------------- There is only one possibility
1.37      www      12547: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12548: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12549: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12550:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12551:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12552:                              $possibles->{$syval} = 1;
                   12553:                          }
1.1172.2.66  raeburn  12554:                      }
                   12555:                      if ($checkforblock) {
1.1172.2.126  raeburn  12556:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12557:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12558:                              if (@blockers) {
                   12559:                                  $syval = '';
                   12560:                                  untie(%bighash);
                   12561:                                  return $env{$cache_str}='';
                   12562:                              }
1.1172.2.66  raeburn  12563:                          }
                   12564:                      }
                   12565:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12566: # ------------------------------------------ There is more than one possibility
                   12567:                      my $realpossible=0;
1.800     albertel 12568:                      foreach my $id (@possibilities) {
                   12569: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12570:                          my $canaccess;
                   12571:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12572:                              $canaccess = 1;
                   12573:                          } else {
                   12574:                              $canaccess = &allowed('bre',$file);
                   12575:                          }
                   12576:                          if ($canaccess) {
                   12577:          		     my ($mapid,$resid)=split(/\./,$id);
                   12578:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12579:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12580:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12581:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12582:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12583:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12584:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12585:                                      if (@blockers > 0) {
                   12586:                                          $syval = '';
                   12587:                                      } else {
1.1172.2.66  raeburn  12588:                                          $syval = $poss_syval;
                   12589:                                          $realpossible++;
                   12590:                                      }
                   12591:                                  } else {
                   12592:                                      $syval = $poss_syval;
                   12593:                                      $realpossible++;
                   12594:                                  }
1.1172.2.126  raeburn  12595:                                  if ($syval) {
                   12596:                                      if (ref($possibles) eq 'HASH') {
                   12597:                                          $possibles->{$syval} = 1;
                   12598:                                      }
                   12599:                                  }
1.1172.2.66  raeburn  12600:                              }
1.39      www      12601: 			 }
1.191     harris41 12602:                      }
1.39      www      12603: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12604:                  } else {
                   12605:                      $syval='';
1.37      www      12606:                  }
                   12607: 	      }
1.1172.2.66  raeburn  12608:               untie(%bighash);
1.481     raeburn  12609:            }
1.31      www      12610:         }
1.62      www      12611:         if ($syval) {
1.1172.2.128  raeburn  12612: 	    return $env{$cache_str}=$syval;
1.62      www      12613:         }
1.31      www      12614:     }
1.949     raeburn  12615:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12616:     return $env{$cache_str}='';
1.31      www      12617: }
                   12618: 
                   12619: # ---------------------------------------------------------- Return random seed
                   12620: 
1.32      www      12621: sub numval {
                   12622:     my $txt=shift;
                   12623:     $txt=~tr/A-J/0-9/;
                   12624:     $txt=~tr/a-j/0-9/;
                   12625:     $txt=~tr/K-T/0-9/;
                   12626:     $txt=~tr/k-t/0-9/;
                   12627:     $txt=~tr/U-Z/0-5/;
                   12628:     $txt=~tr/u-z/0-5/;
                   12629:     $txt=~s/\D//g;
1.564     albertel 12630:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12631:     return int($txt);
1.368     albertel 12632: }
                   12633: 
1.484     albertel 12634: sub numval2 {
                   12635:     my $txt=shift;
                   12636:     $txt=~tr/A-J/0-9/;
                   12637:     $txt=~tr/a-j/0-9/;
                   12638:     $txt=~tr/K-T/0-9/;
                   12639:     $txt=~tr/k-t/0-9/;
                   12640:     $txt=~tr/U-Z/0-5/;
                   12641:     $txt=~tr/u-z/0-5/;
                   12642:     $txt=~s/\D//g;
                   12643:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12644:     my $total;
                   12645:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12646:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12647:     return int($total);
                   12648: }
                   12649: 
1.575     albertel 12650: sub numval3 {
                   12651:     use integer;
                   12652:     my $txt=shift;
                   12653:     $txt=~tr/A-J/0-9/;
                   12654:     $txt=~tr/a-j/0-9/;
                   12655:     $txt=~tr/K-T/0-9/;
                   12656:     $txt=~tr/k-t/0-9/;
                   12657:     $txt=~tr/U-Z/0-5/;
                   12658:     $txt=~tr/u-z/0-5/;
                   12659:     $txt=~s/\D//g;
                   12660:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12661:     my $total;
                   12662:     foreach my $val (@txts) { $total+=$val; }
                   12663:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12664:     return $total;
                   12665: }
                   12666: 
1.675     albertel 12667: sub digest {
                   12668:     my ($data)=@_;
                   12669:     my $digest=&Digest::MD5::md5($data);
                   12670:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12671:     my ($e,$f);
                   12672:     {
                   12673:         use integer;
                   12674:         $e=($a+$b);
                   12675:         $f=($c+$d);
                   12676:         if ($_64bit) {
                   12677:             $e=(($e<<32)>>32);
                   12678:             $f=(($f<<32)>>32);
                   12679:         }
                   12680:     }
                   12681:     if (wantarray) {
                   12682: 	return ($e,$f);
                   12683:     } else {
                   12684: 	my $g;
                   12685: 	{
                   12686: 	    use integer;
                   12687: 	    $g=($e+$f);
                   12688: 	    if ($_64bit) {
                   12689: 		$g=(($g<<32)>>32);
                   12690: 	    }
                   12691: 	}
                   12692: 	return $g;
                   12693:     }
                   12694: }
                   12695: 
1.368     albertel 12696: sub latest_rnd_algorithm_id {
1.675     albertel 12697:     return '64bit5';
1.366     albertel 12698: }
1.32      www      12699: 
1.503     albertel 12700: sub get_rand_alg {
                   12701:     my ($courseid)=@_;
1.790     albertel 12702:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12703:     if ($courseid) {
1.620     albertel 12704: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12705:     }
                   12706:     return &latest_rnd_algorithm_id();
                   12707: }
                   12708: 
1.562     albertel 12709: sub validCODE {
                   12710:     my ($CODE)=@_;
                   12711:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12712:     return 0;
                   12713: }
                   12714: 
1.491     albertel 12715: sub getCODE {
1.620     albertel 12716:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12717:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12718: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12719: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12720: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12721:     }
                   12722:     return undef;
                   12723: }
1.1133    foxr     12724: #
                   12725: #  Determines the random seed for a specific context:
                   12726: #
                   12727: # parameters:
                   12728: #   symb      - in course context the symb for the seed.
                   12729: #   course_id - The course id of the form domain_coursenum.
                   12730: #   domain    - Domain for the user.
                   12731: #   course    - Course for the user.
                   12732: #   cenv      - environment of the course.
                   12733: #
                   12734: # NOTE:
                   12735: #   All parameters are picked out of the environment if missing
                   12736: #   or not defined.
                   12737: #   If a symb cannot be determined the current time is used instead.
                   12738: #
                   12739: #  For a given well defined symb, courside, domain, username,
                   12740: #  and course environment, the seed is reproducible.
                   12741: #
1.31      www      12742: sub rndseed {
1.1133    foxr     12743:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12744:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12745:     if (!defined($symb)) {
1.366     albertel 12746: 	unless ($symb=$wsymb) { return time; }
                   12747:     }
1.1146    foxr     12748:     if (!defined $courseid) { 
                   12749: 	$courseid=$wcourseid; 
                   12750:     }
                   12751:     if (!defined $domain) { $domain=$wdomain; }
                   12752:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12753: 
                   12754:     my $which;
                   12755:     if (defined($cenv->{'rndseed'})) {
                   12756: 	$which = $cenv->{'rndseed'};
                   12757:     } else {
                   12758: 	$which =&get_rand_alg($courseid);
                   12759:     }
1.491     albertel 12760:     if (defined(&getCODE())) {
1.675     albertel 12761: 	if ($which eq '64bit5') {
                   12762: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12763: 	} elsif ($which eq '64bit4') {
1.575     albertel 12764: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12765: 	} else {
                   12766: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12767: 	}
1.675     albertel 12768:     } elsif ($which eq '64bit5') {
                   12769: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12770:     } elsif ($which eq '64bit4') {
                   12771: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12772:     } elsif ($which eq '64bit3') {
                   12773: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12774:     } elsif ($which eq '64bit2') {
                   12775: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12776:     } elsif ($which eq '64bit') {
                   12777: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12778:     }
                   12779:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12780: }
                   12781: 
                   12782: sub rndseed_32bit {
                   12783:     my ($symb,$courseid,$domain,$username)=@_;
                   12784:     {
                   12785: 	use integer;
                   12786: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12787: 	my $symbseed=numval($symb) << 22;
                   12788: 	my $namechck=unpack("%32C*",$username) << 17;
                   12789: 	my $nameseed=numval($username) << 12;
                   12790: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12791: 	my $courseseed=unpack("%32C*",$courseid);
                   12792: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12793: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12794: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12795: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12796: 	return $num;
                   12797:     }
                   12798: }
                   12799: 
                   12800: sub rndseed_64bit {
                   12801:     my ($symb,$courseid,$domain,$username)=@_;
                   12802:     {
                   12803: 	use integer;
                   12804: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12805: 	my $symbseed=numval($symb) << 10;
                   12806: 	my $namechck=unpack("%32S*",$username);
                   12807: 	
                   12808: 	my $nameseed=numval($username) << 21;
                   12809: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12810: 	my $courseseed=unpack("%32S*",$courseid);
                   12811: 	
                   12812: 	my $num1=$symbchck+$symbseed+$namechck;
                   12813: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12814: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12815: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12816: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12817: 	return "$num1,$num2";
1.155     albertel 12818:     }
1.366     albertel 12819: }
                   12820: 
1.443     albertel 12821: sub rndseed_64bit2 {
                   12822:     my ($symb,$courseid,$domain,$username)=@_;
                   12823:     {
                   12824: 	use integer;
                   12825: 	# strings need to be an even # of cahracters long, it it is odd the
                   12826:         # last characters gets thrown away
                   12827: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12828: 	my $symbseed=numval($symb) << 10;
                   12829: 	my $namechck=unpack("%32S*",$username.' ');
                   12830: 	
                   12831: 	my $nameseed=numval($username) << 21;
1.501     albertel 12832: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12833: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12834: 	
                   12835: 	my $num1=$symbchck+$symbseed+$namechck;
                   12836: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12837: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12838: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12839: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12840: 	return "$num1,$num2";
                   12841:     }
                   12842: }
                   12843: 
                   12844: sub rndseed_64bit3 {
                   12845:     my ($symb,$courseid,$domain,$username)=@_;
                   12846:     {
                   12847: 	use integer;
                   12848: 	# strings need to be an even # of cahracters long, it it is odd the
                   12849:         # last characters gets thrown away
                   12850: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12851: 	my $symbseed=numval2($symb) << 10;
                   12852: 	my $namechck=unpack("%32S*",$username.' ');
                   12853: 	
                   12854: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12855: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12856: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12857: 	
                   12858: 	my $num1=$symbchck+$symbseed+$namechck;
                   12859: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12860: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12861: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12862: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12863: 	
1.503     albertel 12864: 	return "$num1:$num2";
1.443     albertel 12865:     }
                   12866: }
                   12867: 
1.575     albertel 12868: sub rndseed_64bit4 {
                   12869:     my ($symb,$courseid,$domain,$username)=@_;
                   12870:     {
                   12871: 	use integer;
                   12872: 	# strings need to be an even # of cahracters long, it it is odd the
                   12873:         # last characters gets thrown away
                   12874: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12875: 	my $symbseed=numval3($symb) << 10;
                   12876: 	my $namechck=unpack("%32S*",$username.' ');
                   12877: 	
                   12878: 	my $nameseed=numval3($username) << 21;
                   12879: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12880: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12881: 	
                   12882: 	my $num1=$symbchck+$symbseed+$namechck;
                   12883: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12884: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12885: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12886: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12887: 	
1.575     albertel 12888: 	return "$num1:$num2";
                   12889:     }
                   12890: }
                   12891: 
1.675     albertel 12892: sub rndseed_64bit5 {
                   12893:     my ($symb,$courseid,$domain,$username)=@_;
                   12894:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12895:     return "$num1:$num2";
                   12896: }
                   12897: 
1.366     albertel 12898: sub rndseed_CODE_64bit {
                   12899:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12900:     {
1.366     albertel 12901: 	use integer;
1.443     albertel 12902: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12903: 	my $symbseed=numval2($symb);
1.491     albertel 12904: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12905: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12906: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12907: 	my $num1=$symbseed+$CODEchck;
                   12908: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12909: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12910: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12911: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12912: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12913: 	return "$num1:$num2";
1.366     albertel 12914:     }
                   12915: }
                   12916: 
1.575     albertel 12917: sub rndseed_CODE_64bit4 {
                   12918:     my ($symb,$courseid,$domain,$username)=@_;
                   12919:     {
                   12920: 	use integer;
                   12921: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12922: 	my $symbseed=numval3($symb);
                   12923: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12924: 	my $CODEseed=numval3(&getCODE());
                   12925: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12926: 	my $num1=$symbseed+$CODEchck;
                   12927: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12928: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12929: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12930: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12931: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12932: 	return "$num1:$num2";
                   12933:     }
                   12934: }
                   12935: 
1.675     albertel 12936: sub rndseed_CODE_64bit5 {
                   12937:     my ($symb,$courseid,$domain,$username)=@_;
                   12938:     my $code = &getCODE();
                   12939:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12940:     return "$num1:$num2";
                   12941: }
                   12942: 
1.366     albertel 12943: sub setup_random_from_rndseed {
                   12944:     my ($rndseed)=@_;
1.503     albertel 12945:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12946: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12947:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12948:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12949:         } else {
                   12950:             &Math::Random::random_set_seed($num1,$num2);
                   12951:         }
1.366     albertel 12952:     } else {
                   12953: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12954:     }
1.36      albertel 12955: }
                   12956: 
1.474     albertel 12957: sub latest_receipt_algorithm_id {
1.835     albertel 12958:     return 'receipt3';
1.474     albertel 12959: }
                   12960: 
1.480     www      12961: sub recunique {
                   12962:     my $fucourseid=shift;
                   12963:     my $unique;
1.835     albertel 12964:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12965: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12966: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12967:     } else {
                   12968: 	$unique=$perlvar{'lonReceipt'};
                   12969:     }
                   12970:     return unpack("%32C*",$unique);
                   12971: }
                   12972: 
                   12973: sub recprefix {
                   12974:     my $fucourseid=shift;
                   12975:     my $prefix;
1.835     albertel 12976:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12977: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12978: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12979:     } else {
                   12980: 	$prefix=$perlvar{'lonHostID'};
                   12981:     }
                   12982:     return unpack("%32C*",$prefix);
                   12983: }
                   12984: 
1.76      www      12985: sub ireceipt {
1.474     albertel 12986:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12987: 
                   12988:     my $return =&recprefix($fucourseid).'-';
                   12989: 
                   12990:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12991: 	$env{'request.state'} eq 'construct') {
                   12992: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12993: 	return $return;
                   12994:     }
                   12995: 
1.76      www      12996:     my $cuname=unpack("%32C*",$funame);
                   12997:     my $cudom=unpack("%32C*",$fudom);
                   12998:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12999:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13000:     my $cunique=&recunique($fucourseid);
1.474     albertel 13001:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13002:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13003: 
1.790     albertel 13004: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13005: 			       
                   13006: 	$return.= ($cunique%$cuname+
                   13007: 		   $cunique%$cudom+
                   13008: 		   $cusymb%$cuname+
                   13009: 		   $cusymb%$cudom+
                   13010: 		   $cucourseid%$cuname+
                   13011: 		   $cucourseid%$cudom+
                   13012: 		   $cpart%$cuname+
                   13013: 		   $cpart%$cudom);
                   13014:     } else {
                   13015: 	$return.= ($cunique%$cuname+
                   13016: 		   $cunique%$cudom+
                   13017: 		   $cusymb%$cuname+
                   13018: 		   $cusymb%$cudom+
                   13019: 		   $cucourseid%$cuname+
                   13020: 		   $cucourseid%$cudom);
                   13021:     }
                   13022:     return $return;
1.76      www      13023: }
                   13024: 
                   13025: sub receipt {
1.474     albertel 13026:     my ($part)=@_;
1.790     albertel 13027:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13028:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13029: }
1.260     ng       13030: 
1.790     albertel 13031: sub whichuser {
                   13032:     my ($passedsymb)=@_;
                   13033:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13034:     if (defined($env{'form.grade_symb'})) {
                   13035: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13036: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13037: 	if (!$allowed &&
                   13038: 	    exists($env{'request.course.sec'}) &&
                   13039: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13040: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13041: 			      '/'.$env{'request.course.sec'});
                   13042: 	}
                   13043: 	if ($allowed) {
                   13044: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13045: 	    $courseid=$tmp_courseid;
                   13046: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13047: 	    ($name)=&get_env_multiple('form.grade_username');
                   13048: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13049: 	}
                   13050:     }
                   13051:     if (!$passedsymb) {
                   13052: 	$symb=&symbread();
                   13053:     } else {
                   13054: 	$symb=$passedsymb;
                   13055:     }
                   13056:     $courseid=$env{'request.course.id'};
                   13057:     $domain=$env{'user.domain'};
                   13058:     $name=$env{'user.name'};
                   13059:     if ($name eq 'public' && $domain eq 'public') {
                   13060: 	if (!defined($env{'form.username'})) {
                   13061: 	    $env{'form.username'}.=time.rand(10000000);
                   13062: 	}
                   13063: 	$name.=$env{'form.username'};
                   13064:     }
                   13065:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13066: 
                   13067: }
                   13068: 
1.36      albertel 13069: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13070: # returns either the contents of the file or 
                   13071: # -1 if the file doesn't exist
1.481     raeburn  13072: #
                   13073: # if the target is a file that was uploaded via DOCS, 
                   13074: # a check will be made to see if a current copy exists on the local server,
                   13075: # if it does this will be served, otherwise a copy will be retrieved from
                   13076: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13077: # the local server.   
1.472     albertel 13078: 
1.36      albertel 13079: sub getfile {
1.538     albertel 13080:     my ($file) = @_;
1.609     banghart 13081:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13082:     &repcopy($file);
                   13083:     return &readfile($file);
                   13084: }
                   13085: 
                   13086: sub repcopy_userfile {
                   13087:     my ($file)=@_;
1.1142    raeburn  13088:     my $londocroot = $perlvar{'lonDocRoot'};
                   13089:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13090:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13091:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13092: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13093:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13094:     if (-e "$file") {
1.828     www      13095: # we already have a local copy, check it out
1.538     albertel 13096: 	my @fileinfo = stat($file);
1.828     www      13097: 	my $rtncode;
                   13098: 	my $info;
1.538     albertel 13099: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13100: 	if ($lwpresp ne 'ok') {
1.828     www      13101: # there is no such file anymore, even though we had a local copy
1.482     albertel 13102: 	    if ($rtncode eq '404') {
1.538     albertel 13103: 		unlink($file);
1.482     albertel 13104: 	    }
                   13105: 	    return -1;
                   13106: 	}
                   13107: 	if ($info < $fileinfo[9]) {
1.828     www      13108: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13109: 	    return 'ok';
1.828     www      13110: 	} else {
                   13111: # the file is outdated, get rid of it
                   13112: 	    unlink($file);
1.482     albertel 13113: 	}
1.828     www      13114:     }
                   13115: # one way or the other, at this point, we don't have the file
                   13116: # construct the correct path for the file
                   13117:     my @parts = ($cdom,$cnum); 
                   13118:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13119: 	push @parts, split(/\//,$1);
                   13120:     }
                   13121:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13122:     foreach my $part (@parts) {
                   13123: 	$path .= '/'.$part;
                   13124: 	if (!-e $path) {
                   13125: 	    mkdir($path,0770);
1.482     albertel 13126: 	}
                   13127:     }
1.828     www      13128: # now the path exists for sure
                   13129: # get a user agent
                   13130:     my $ua=new LWP::UserAgent;
                   13131:     my $transferfile=$file.'.in.transfer';
                   13132: # FIXME: this should flock
                   13133:     if (-e $transferfile) { return 'ok'; }
                   13134:     my $request;
                   13135:     $uri=~s/^\///;
1.980     raeburn  13136:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13137:     my $hostname = &hostname($homeserver);
1.980     raeburn  13138:     my $protocol = $protocol{$homeserver};
                   13139:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13140:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13141:     my $response=$ua->request($request,$transferfile);
                   13142: # did it work?
                   13143:     if ($response->is_error()) {
                   13144: 	unlink($transferfile);
                   13145: 	&logthis("Userfile repcopy failed for $uri");
                   13146: 	return -1;
                   13147:     }
                   13148: # worked, rename the transfer file
                   13149:     rename($transferfile,$file);
1.607     raeburn  13150:     return 'ok';
1.481     raeburn  13151: }
                   13152: 
1.517     albertel 13153: sub tokenwrapper {
                   13154:     my $uri=shift;
1.980     raeburn  13155:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13156:     $uri=~s|^/||;
1.620     albertel 13157:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13158:     my $token=$1;
1.552     albertel 13159:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13160:     if ($udom && $uname && $file) {
                   13161: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13162:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13163:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13164:         my $hostname = &hostname($homeserver);
1.980     raeburn  13165:         my $protocol = $protocol{$homeserver};
                   13166:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13167:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13168:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13169:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13170:     } else {
                   13171:         return '/adm/notfound.html';
                   13172:     }
                   13173: }
                   13174: 
1.828     www      13175: # call with reqtype HEAD: get last modification time
                   13176: # call with reqtype GET: get the file contents
                   13177: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13178: #
1.481     raeburn  13179: sub getuploaded {
                   13180:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13181:     $uri=~s/^\///;
1.980     raeburn  13182:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13183:     my $hostname = &hostname($homeserver);
1.980     raeburn  13184:     my $protocol = $protocol{$homeserver};
                   13185:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13186:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13187:     my $ua=new LWP::UserAgent;
                   13188:     my $request=new HTTP::Request($reqtype,$uri);
                   13189:     my $response=$ua->request($request);
                   13190:     $$rtncode = $response->code;
1.482     albertel 13191:     if (! $response->is_success()) {
                   13192: 	return 'failed';
                   13193:     }      
                   13194:     if ($reqtype eq 'HEAD') {
1.486     www      13195: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13196:     } elsif ($reqtype eq 'GET') {
                   13197: 	$$info = $response->content;
1.472     albertel 13198:     }
1.482     albertel 13199:     return 'ok';
1.36      albertel 13200: }
                   13201: 
1.481     raeburn  13202: sub readfile {
                   13203:     my $file = shift;
                   13204:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13205:     my $fh;
1.1172.2.96  raeburn  13206:     open($fh,"<",$file);
1.481     raeburn  13207:     my $a='';
1.800     albertel 13208:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13209:     return $a;
                   13210: }
                   13211: 
1.36      albertel 13212: sub filelocation {
1.590     banghart 13213:     my ($dir,$file) = @_;
                   13214:     my $location;
                   13215:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13216: 
                   13217:     if ($file =~ m-^/adm/-) {
                   13218: 	$file=~s-^/adm/wrapper/-/-;
                   13219: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13220:     }
1.882     albertel 13221: 
1.1139    www      13222:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13223:         $location = $file;
1.609     banghart 13224:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13225:         my ($udom,$uname,$filename)=
1.811     albertel 13226:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13227:         my $home=&homeserver($uname,$udom);
                   13228:         my $is_me=0;
                   13229:         my @ids=&current_machine_ids();
                   13230:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13231:         if ($is_me) {
1.1117    foxr     13232:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13233:         } else {
                   13234:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13235:   	      $udom.'/'.$uname.'/'.$filename;
                   13236:         }
1.882     albertel 13237:     } elsif ($file =~ m-^/adm/-) {
                   13238: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13239:     } else {
                   13240:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13241:         $file=~s:^/(res|priv)/:/:;
                   13242:         my $space=$1;
1.590     banghart 13243:         if ( !( $file =~ m:^/:) ) {
                   13244:             $location = $dir. '/'.$file;
                   13245:         } else {
1.1142    raeburn  13246:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13247:         }
1.59      albertel 13248:     }
1.590     banghart 13249:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13250:     while ($location=~m{/\.\./}) {
                   13251: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13252: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13253: 	} else {
                   13254: 	    $location=~ s{/\.\./}{/}g;
                   13255: 	}
                   13256:     } #remove dir/..
1.590     banghart 13257:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13258:     return $location;
1.46      www      13259: }
1.36      albertel 13260: 
1.46      www      13261: sub hreflocation {
                   13262:     my ($dir,$file)=@_;
1.980     raeburn  13263:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13264: 	$file=filelocation($dir,$file);
1.700     albertel 13265:     } elsif ($file=~m-^/adm/-) {
                   13266: 	$file=~s-^/adm/wrapper/-/-;
                   13267: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13268:     }
                   13269:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13270: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13271:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13272: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13273: 	        {/uploaded/$1/$2/}x;
1.46      www      13274:     }
1.913     albertel 13275:     if ($file=~ m{^/userfiles/}) {
                   13276: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13277:     }
1.462     albertel 13278:     return $file;
1.465     albertel 13279: }
                   13280: 
1.1139    www      13281: 
                   13282: 
                   13283: 
                   13284: 
1.465     albertel 13285: sub current_machine_domains {
1.853     albertel 13286:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13287: }
                   13288: 
                   13289: sub machine_domains {
                   13290:     my ($hostname) = @_;
1.465     albertel 13291:     my @domains;
1.838     albertel 13292:     my %hostname = &all_hostnames();
1.465     albertel 13293:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13294: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13295: 	if ($hostname eq $name) {
1.844     albertel 13296: 	    push(@domains,&host_domain($id));
1.465     albertel 13297: 	}
                   13298:     }
                   13299:     return @domains;
                   13300: }
                   13301: 
                   13302: sub current_machine_ids {
1.853     albertel 13303:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13304: }
                   13305: 
                   13306: sub machine_ids {
                   13307:     my ($hostname) = @_;
                   13308:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13309:     my @ids;
1.888     albertel 13310:     my %name_to_host = &all_names();
1.889     albertel 13311:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13312: 	return @{ $name_to_host{$hostname} };
                   13313:     }
                   13314:     return;
1.31      www      13315: }
                   13316: 
1.824     raeburn  13317: sub additional_machine_domains {
                   13318:     my @domains;
1.1172.2.96  raeburn  13319:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13320:     while( my $line = <$fh>) {
                   13321:         $line =~ s/\s//g;
                   13322:         push(@domains,$line);
                   13323:     }
                   13324:     return @domains;
                   13325: }
                   13326: 
                   13327: sub default_login_domain {
                   13328:     my $domain = $perlvar{'lonDefDomain'};
                   13329:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13330:     foreach my $posdom (&current_machine_domains(),
                   13331:                         &additional_machine_domains()) {
                   13332:         if (lc($posdom) eq lc($testdomain)) {
                   13333:             $domain=$posdom;
                   13334:             last;
                   13335:         }
                   13336:     }
                   13337:     return $domain;
                   13338: }
                   13339: 
1.1172.2.106  raeburn  13340: sub shared_institution {
                   13341:     my ($dom) = @_;
                   13342:     my $same_intdom;
                   13343:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13344:     if ($hostintdom ne '') {
                   13345:         my %iphost = &get_iphost();
                   13346:         my $primary_id = &domain($dom,'primary');
                   13347:         my $primary_ip = &get_host_ip($primary_id);
                   13348:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13349:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13350:                 my $intdom = &internet_dom($id);
                   13351:                 if ($intdom eq $hostintdom) {
                   13352:                     $same_intdom = 1;
                   13353:                     last;
                   13354:                 }
                   13355:             }
                   13356:         }
                   13357:     }
                   13358:     return $same_intdom;
                   13359: }
                   13360: 
1.1172.2.120  raeburn  13361: sub uses_sts {
                   13362:     my ($ignore_cache) = @_;
                   13363:     my $lonhost = $perlvar{'lonHostID'};
                   13364:     my $hostname = &hostname($lonhost);
                   13365:     my $sts_on;
                   13366:     if ($protocol{$lonhost} eq 'https') {
                   13367:         my $cachetime = 12*3600;
                   13368:         if (!$ignore_cache) {
                   13369:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13370:             if (defined($cached)) {
                   13371:                 return $sts_on;
                   13372:             }
                   13373:         }
1.1172.2.121  raeburn  13374:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13375:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13376:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13377:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13378:         if ($response->is_success) {
                   13379:             my $has_sts = $response->header('Strict-Transport-Security');
                   13380:             if ($has_sts eq '') {
                   13381:                 $sts_on = 0;
                   13382:             } else {
                   13383:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13384:                     my $maxage = $1;
                   13385:                     if ($maxage) {
                   13386:                         $sts_on = 1;
                   13387:                     } else {
                   13388:                         $sts_on = 0;
                   13389:                     }
                   13390:                 } else {
                   13391:                     $sts_on = 0;
                   13392:                 }
                   13393:             }
                   13394:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13395:         }
                   13396:     }
                   13397:     return;
                   13398: }
                   13399: 
1.31      www      13400: # ------------------------------------------------------------- Declutters URLs
                   13401: 
                   13402: sub declutter {
                   13403:     my $thisfn=shift;
1.569     albertel 13404:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13405:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13406:         $thisfn=~s{^/home/httpd/html}{};
                   13407:     }
1.31      www      13408:     $thisfn=~s/^\///;
1.697     albertel 13409:     $thisfn=~s|^adm/wrapper/||;
                   13410:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13411:     $thisfn=~s/^res\///;
1.1172    bisitz   13412:     $thisfn=~s/^priv\///;
1.1032    raeburn  13413:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13414:         $thisfn=~s/\?.+$//;
                   13415:     }
1.268     www      13416:     return $thisfn;
                   13417: }
                   13418: 
                   13419: # ------------------------------------------------------------- Clutter up URLs
                   13420: 
                   13421: sub clutter {
                   13422:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13423:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13424: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13425:        $thisfn='/res'.$thisfn; 
                   13426:     }
1.1031    raeburn  13427:     if ($thisfn !~m|^/adm|) {
                   13428: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13429: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13430: 	} else {
                   13431: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13432: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13433: 	    if ($embstyle eq 'ssi'
                   13434: 		|| ($embstyle eq 'hdn')
                   13435: 		|| ($embstyle eq 'rat')
                   13436: 		|| ($embstyle eq 'prv')
                   13437: 		|| ($embstyle eq 'ign')) {
                   13438: 		#do nothing with these
                   13439: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13440: 		|| ($embstyle eq 'emb')
                   13441: 		|| ($embstyle eq 'wrp')) {
                   13442: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13443: 	    } elsif ($embstyle eq 'unk'
                   13444: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13445: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13446: 	    } else {
1.718     www      13447: #		&logthis("Got a blank emb style");
1.695     albertel 13448: 	    }
1.694     albertel 13449: 	}
                   13450:     }
1.31      www      13451:     return $thisfn;
1.12      www      13452: }
                   13453: 
1.787     albertel 13454: sub clutter_with_no_wrapper {
                   13455:     my $uri = &clutter(shift);
                   13456:     if ($uri =~ m-^/adm/-) {
                   13457: 	$uri =~ s-^/adm/wrapper/-/-;
                   13458: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13459:     }
                   13460:     return $uri;
                   13461: }
                   13462: 
1.557     albertel 13463: sub freeze_escape {
                   13464:     my ($value)=@_;
                   13465:     if (ref($value)) {
                   13466: 	$value=&nfreeze($value);
                   13467: 	return '__FROZEN__'.&escape($value);
                   13468:     }
                   13469:     return &escape($value);
                   13470: }
                   13471: 
1.11      www      13472: 
1.557     albertel 13473: sub thaw_unescape {
                   13474:     my ($value)=@_;
                   13475:     if ($value =~ /^__FROZEN__/) {
                   13476: 	substr($value,0,10,undef);
                   13477: 	$value=&unescape($value);
                   13478: 	return &thaw($value);
                   13479:     }
                   13480:     return &unescape($value);
                   13481: }
                   13482: 
1.436     albertel 13483: sub correct_line_ends {
                   13484:     my ($result)=@_;
                   13485:     $$result =~s/\r\n/\n/mg;
                   13486:     $$result =~s/\r/\n/mg;
1.415     albertel 13487: }
1.1       albertel 13488: # ================================================================ Main Program
                   13489: 
1.184     www      13490: sub goodbye {
1.204     albertel 13491:    &logthis("Starting Shut down");
1.443     albertel 13492: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13493:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13494: #converted
1.599     albertel 13495: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13496:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13497: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13498: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13499: #1.1 only
1.870     albertel 13500: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13501: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13502: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13503: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13504:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13505:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13506:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13507:    &flushcourselogs();
                   13508:    &logthis("Shutting down");
                   13509: }
                   13510: 
1.852     albertel 13511: sub get_dns {
1.1172.2.17  raeburn  13512:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13513:     if (!$ignore_cache) {
                   13514: 	my ($content,$cached)=
                   13515: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13516: 	if ($cached) {
1.1172.2.17  raeburn  13517: 	    &$func($content,$hashref);
1.869     albertel 13518: 	    return;
                   13519: 	}
                   13520:     }
                   13521: 
                   13522:     my %alldns;
1.1172.2.96  raeburn  13523:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13524:         foreach my $dns (<$config>) {
                   13525: 	    next if ($dns !~ /^\^(\S*)/x);
                   13526:             my $line = $1;
                   13527:             my ($host,$protocol) = split(/:/,$line);
                   13528:             if ($protocol ne 'https') {
                   13529:                 $protocol = 'http';
                   13530:             }
                   13531: 	    $alldns{$host} = $protocol;
1.979     raeburn  13532:         }
1.1172.2.96  raeburn  13533:         close($config);
1.869     albertel 13534:     }
                   13535:     while (%alldns) {
1.1172.2.52  raeburn  13536: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13537: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13538:         $ua->timeout(30);
1.979     raeburn  13539: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13540: 	my $response=$ua->request($request);
1.979     raeburn  13541:         delete($alldns{$dns});
1.852     albertel 13542: 	next if ($response->is_error());
                   13543: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13544:         unless ($nocache) {
1.1172.2.23  raeburn  13545: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13546:         }
                   13547: 	&$func(\@content,$hashref);
1.869     albertel 13548: 	return;
1.852     albertel 13549:     }
1.871     albertel 13550:     my $which = (split('/',$url))[3];
                   13551:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13552:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13553:         my @content = <$config>;
                   13554:         &$func(\@content,$hashref);
                   13555:     }
1.1172.2.17  raeburn  13556:     return;
                   13557: }
                   13558: 
                   13559: # ------------------------------------------------------Get DNS checksums file
                   13560: sub parse_dns_checksums_tab {
                   13561:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13562:     my $lonhost = $perlvar{'lonHostID'};
                   13563:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13564:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13565:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13566:     my $webconfdir = '/etc/httpd/conf';
                   13567:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13568:         $webconfdir = '/etc/apache2';
                   13569:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13570:         if ($1 >= 10) {
                   13571:             $webconfdir = '/etc/apache2';
                   13572:         }
                   13573:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13574:         if ($1 >= 10.0) {
                   13575:             $webconfdir = '/etc/apache2';
                   13576:         }
                   13577:     }
1.1172.2.17  raeburn  13578:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13579:     my (%chksum,%revnum);
                   13580:     if (ref($lines) eq 'ARRAY') {
                   13581:         chomp(@{$lines});
1.1172.2.34  raeburn  13582:         my $version = shift(@{$lines});
                   13583:         if ($version eq $release) {
1.1172.2.17  raeburn  13584:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13585:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13586:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13587:                     if ($webconfdir eq '/etc/apache2') {
                   13588:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13589:                     }
                   13590:                 }
1.1172.2.34  raeburn  13591:                 $chksum{$file} = $shasum;
                   13592:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13593:             }
                   13594:             if (ref($hashref) eq 'HASH') {
                   13595:                 %{$hashref} = (
                   13596:                                 sums     => \%chksum,
                   13597:                                 versions => \%revnum,
                   13598:                               );
                   13599:             }
                   13600:         }
                   13601:     }
1.869     albertel 13602:     return;
1.852     albertel 13603: }
1.1172.2.17  raeburn  13604: 
                   13605: sub fetch_dns_checksums {
                   13606:     my %checksums;
1.1172.2.34  raeburn  13607:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13608:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13609:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13610:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13611:              \%checksums);
                   13612:     return \%checksums;
                   13613: }
                   13614: 
1.327     albertel 13615: # ------------------------------------------------------------ Read domain file
                   13616: {
1.852     albertel 13617:     my $loaded;
1.846     albertel 13618:     my %domain;
                   13619: 
1.852     albertel 13620:     sub parse_domain_tab {
                   13621: 	my ($lines) = @_;
                   13622: 	foreach my $line (@$lines) {
                   13623: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13624: 
1.846     albertel 13625: 	    chomp($line);
1.852     albertel 13626: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13627: 	    my %this_domain;
                   13628: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13629: 			       'lang_def', 'city', 'longi', 'lati',
                   13630: 			       'primary') {
                   13631: 		$this_domain{$field} = shift(@elements);
                   13632: 	    }
                   13633: 	    $domain{$name} = \%this_domain;
1.852     albertel 13634: 	}
                   13635:     }
1.864     albertel 13636: 
                   13637:     sub reset_domain_info {
                   13638: 	undef($loaded);
                   13639: 	undef(%domain);
                   13640:     }
                   13641: 
1.852     albertel 13642:     sub load_domain_tab {
1.1172.2.70  raeburn  13643: 	my ($ignore_cache,$nocache) = @_;
                   13644: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13645: 	my $fh;
1.1172.2.96  raeburn  13646: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13647: 	    my @lines = <$fh>;
                   13648: 	    &parse_domain_tab(\@lines);
1.448     albertel 13649: 	}
1.852     albertel 13650: 	close($fh);
                   13651: 	$loaded = 1;
1.327     albertel 13652:     }
1.846     albertel 13653: 
                   13654:     sub domain {
1.852     albertel 13655: 	&load_domain_tab() if (!$loaded);
                   13656: 
1.846     albertel 13657: 	my ($name,$what) = @_;
                   13658: 	return if ( !exists($domain{$name}) );
                   13659: 
                   13660: 	if (!$what) {
                   13661: 	    return $domain{$name}{'description'};
                   13662: 	}
                   13663: 	return $domain{$name}{$what};
                   13664:     }
1.974     raeburn  13665: 
                   13666:     sub domain_info {
                   13667:         &load_domain_tab() if (!$loaded);
                   13668:         return %domain;
                   13669:     }
                   13670: 
1.327     albertel 13671: }
                   13672: 
                   13673: 
1.1       albertel 13674: # ------------------------------------------------------------- Read hosts file
                   13675: {
1.838     albertel 13676:     my %hostname;
1.844     albertel 13677:     my %hostdom;
1.845     albertel 13678:     my %libserv;
1.852     albertel 13679:     my $loaded;
1.888     albertel 13680:     my %name_to_host;
1.1074    raeburn  13681:     my %internetdom;
1.1107    raeburn  13682:     my %LC_dns_serv;
1.852     albertel 13683: 
                   13684:     sub parse_hosts_tab {
                   13685: 	my ($file) = @_;
                   13686: 	foreach my $configline (@$file) {
                   13687: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13688:             chomp($configline);
                   13689: 	    if ($configline =~ /^\^/) {
                   13690:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13691:                     $LC_dns_serv{$1} = 1;
                   13692:                 }
                   13693:                 next;
                   13694:             }
1.1074    raeburn  13695: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13696: 	    $name=~s/\s//g;
                   13697: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13698:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13699:                     my $curr = $hostname{$id};
                   13700:                     my $skip;
                   13701:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13702:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13703:                             $skip = 1;
                   13704:                         } else {
                   13705:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13706:                         }
                   13707:                     }
                   13708:                     unless ($skip) {
                   13709:                         push(@{$name_to_host{$name}},$id);
                   13710:                     }
                   13711:                 } else {
                   13712:                     push(@{$name_to_host{$name}},$id);
                   13713:                 }
1.852     albertel 13714: 		$hostname{$id}=$name;
                   13715: 		$hostdom{$id}=$domain;
                   13716: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13717:                 if (defined($protocol)) {
                   13718:                     if ($protocol eq 'https') {
                   13719:                         $protocol{$id} = $protocol;
                   13720:                     } else {
                   13721:                         $protocol{$id} = 'http'; 
                   13722:                     }
1.968     raeburn  13723:                 } else {
1.969     raeburn  13724:                     $protocol{$id} = 'http';
1.968     raeburn  13725:                 }
1.1074    raeburn  13726:                 if (defined($intdom)) {
                   13727:                     $internetdom{$id} = $intdom;
                   13728:                 }
1.852     albertel 13729: 	    }
                   13730: 	}
                   13731:     }
1.864     albertel 13732:     
                   13733:     sub reset_hosts_info {
1.897     albertel 13734: 	&purge_remembered();
1.864     albertel 13735: 	&reset_domain_info();
                   13736: 	&reset_hosts_ip_info();
1.892     albertel 13737: 	undef(%name_to_host);
1.864     albertel 13738: 	undef(%hostname);
                   13739: 	undef(%hostdom);
                   13740: 	undef(%libserv);
                   13741: 	undef($loaded);
                   13742:     }
1.1       albertel 13743: 
1.852     albertel 13744:     sub load_hosts_tab {
1.1172.2.70  raeburn  13745: 	my ($ignore_cache,$nocache) = @_;
                   13746: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13747: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13748: 	my @config = <$config>;
                   13749: 	&parse_hosts_tab(\@config);
                   13750: 	close($config);
                   13751: 	$loaded=1;
1.1       albertel 13752:     }
1.852     albertel 13753: 
1.838     albertel 13754:     sub hostname {
1.852     albertel 13755: 	&load_hosts_tab() if (!$loaded);
                   13756: 
1.838     albertel 13757: 	my ($lonid) = @_;
                   13758: 	return $hostname{$lonid};
                   13759:     }
1.845     albertel 13760: 
1.838     albertel 13761:     sub all_hostnames {
1.852     albertel 13762: 	&load_hosts_tab() if (!$loaded);
                   13763: 
1.838     albertel 13764: 	return %hostname;
                   13765:     }
1.845     albertel 13766: 
1.888     albertel 13767:     sub all_names {
1.1172.2.70  raeburn  13768:         my ($ignore_cache,$nocache) = @_;
                   13769: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13770: 
                   13771: 	return %name_to_host;
                   13772:     }
                   13773: 
1.974     raeburn  13774:     sub all_host_domain {
                   13775:         &load_hosts_tab() if (!$loaded);
                   13776:         return %hostdom;
                   13777:     }
                   13778: 
1.845     albertel 13779:     sub is_library {
1.852     albertel 13780: 	&load_hosts_tab() if (!$loaded);
                   13781: 
1.845     albertel 13782: 	return exists($libserv{$_[0]});
                   13783:     }
                   13784: 
                   13785:     sub all_library {
1.852     albertel 13786: 	&load_hosts_tab() if (!$loaded);
                   13787: 
1.845     albertel 13788: 	return %libserv;
                   13789:     }
                   13790: 
1.1062    droeschl 13791:     sub unique_library {
                   13792: 	#2x reverse removes all hostnames that appear more than once
                   13793:         my %unique = reverse &all_library();
                   13794:         return reverse %unique;
                   13795:     }
                   13796: 
1.841     albertel 13797:     sub get_servers {
1.852     albertel 13798: 	&load_hosts_tab() if (!$loaded);
                   13799: 
1.841     albertel 13800: 	my ($domain,$type) = @_;
                   13801: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13802: 	                                          : %hostname;
                   13803: 	my %result;
1.842     albertel 13804: 	if (ref($domain) eq 'ARRAY') {
                   13805: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13806: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13807: 		    $result{$host} = $hostname;
                   13808: 		}
                   13809: 	    }
                   13810: 	} else {
                   13811: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13812: 		if ($hostdom{$host} eq $domain) {
                   13813: 		    $result{$host} = $hostname;
                   13814: 		}
1.841     albertel 13815: 	    }
                   13816: 	}
                   13817: 	return %result;
                   13818:     }
1.845     albertel 13819: 
1.1062    droeschl 13820:     sub get_unique_servers {
                   13821:         my %unique = reverse &get_servers(@_);
                   13822: 	return reverse %unique;
                   13823:     }
                   13824: 
1.844     albertel 13825:     sub host_domain {
1.852     albertel 13826: 	&load_hosts_tab() if (!$loaded);
                   13827: 
1.844     albertel 13828: 	my ($lonid) = @_;
                   13829: 	return $hostdom{$lonid};
                   13830:     }
                   13831: 
1.841     albertel 13832:     sub all_domains {
1.852     albertel 13833: 	&load_hosts_tab() if (!$loaded);
                   13834: 
1.841     albertel 13835: 	my %seen;
                   13836: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13837: 	return @uniq;
                   13838:     }
1.1074    raeburn  13839: 
                   13840:     sub internet_dom {
                   13841:         &load_hosts_tab() if (!$loaded);
                   13842: 
                   13843:         my ($lonid) = @_;
                   13844:         return $internetdom{$lonid};
                   13845:     }
1.1107    raeburn  13846: 
                   13847:     sub is_LC_dns {
                   13848:         &load_hosts_tab() if (!$loaded);
                   13849: 
                   13850:         my ($hostname) = @_;
                   13851:         return exists($LC_dns_serv{$hostname});
                   13852:     }
                   13853: 
1.1       albertel 13854: }
                   13855: 
1.847     albertel 13856: { 
                   13857:     my %iphost;
1.856     albertel 13858:     my %name_to_ip;
                   13859:     my %lonid_to_ip;
1.869     albertel 13860: 
1.847     albertel 13861:     sub get_hosts_from_ip {
                   13862: 	my ($ip) = @_;
                   13863: 	my %iphosts = &get_iphost();
                   13864: 	if (ref($iphosts{$ip})) {
                   13865: 	    return @{$iphosts{$ip}};
                   13866: 	}
                   13867: 	return;
1.839     albertel 13868:     }
1.864     albertel 13869:     
                   13870:     sub reset_hosts_ip_info {
                   13871: 	undef(%iphost);
                   13872: 	undef(%name_to_ip);
                   13873: 	undef(%lonid_to_ip);
                   13874:     }
1.856     albertel 13875: 
                   13876:     sub get_host_ip {
                   13877: 	my ($lonid) = @_;
                   13878: 	if (exists($lonid_to_ip{$lonid})) {
                   13879: 	    return $lonid_to_ip{$lonid};
                   13880: 	}
                   13881: 	my $name=&hostname($lonid);
                   13882:    	my $ip = gethostbyname($name);
                   13883: 	return if (!$ip || length($ip) ne 4);
                   13884: 	$ip=inet_ntoa($ip);
                   13885: 	$name_to_ip{$name}   = $ip;
                   13886: 	$lonid_to_ip{$lonid} = $ip;
                   13887: 	return $ip;
                   13888:     }
1.847     albertel 13889:     
                   13890:     sub get_iphost {
1.1172.2.70  raeburn  13891: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13892: 
1.869     albertel 13893: 	if (!$ignore_cache) {
                   13894: 	    if (%iphost) {
                   13895: 		return %iphost;
                   13896: 	    }
                   13897: 	    my ($ip_info,$cached)=
                   13898: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13899: 	    if ($cached) {
                   13900: 		%iphost      = %{$ip_info->[0]};
                   13901: 		%name_to_ip  = %{$ip_info->[1]};
                   13902: 		%lonid_to_ip = %{$ip_info->[2]};
                   13903: 		return %iphost;
                   13904: 	    }
                   13905: 	}
1.894     albertel 13906: 
                   13907: 	# get yesterday's info for fallback
                   13908: 	my %old_name_to_ip;
                   13909: 	my ($ip_info,$cached)=
                   13910: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13911: 	if ($cached) {
                   13912: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13913: 	}
                   13914: 
1.1172.2.70  raeburn  13915: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13916: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13917: 	    my $ip;
                   13918: 	    if (!exists($name_to_ip{$name})) {
                   13919: 		$ip = gethostbyname($name);
                   13920: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13921: 		    if (defined($old_name_to_ip{$name})) {
                   13922: 			$ip = $old_name_to_ip{$name};
                   13923: 			&logthis("Can't find $name defaulting to old $ip");
                   13924: 		    } else {
                   13925: 			&logthis("Name $name no IP found");
                   13926: 			next;
                   13927: 		    }
                   13928: 		} else {
                   13929: 		    $ip=inet_ntoa($ip);
1.847     albertel 13930: 		}
                   13931: 		$name_to_ip{$name} = $ip;
                   13932: 	    } else {
                   13933: 		$ip = $name_to_ip{$name};
1.653     albertel 13934: 	    }
1.888     albertel 13935: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13936: 		$lonid_to_ip{$id} = $ip;
                   13937: 	    }
                   13938: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13939: 	}
1.1172.2.70  raeburn  13940:         unless ($nocache) {
                   13941: 	    &do_cache_new('iphost','iphost',
                   13942: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13943: 		          48*60*60);
                   13944:         }
1.869     albertel 13945: 
1.847     albertel 13946: 	return %iphost;
1.598     albertel 13947:     }
                   13948: 
1.992     raeburn  13949:     #
                   13950:     #  Given a DNS returns the loncapa host name for that DNS 
                   13951:     # 
                   13952:     sub host_from_dns {
                   13953:         my ($dns) = @_;
                   13954:         my @hosts;
                   13955:         my $ip;
                   13956: 
1.993     raeburn  13957:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13958:             $ip = $name_to_ip{$dns};
                   13959:         }
                   13960:         if (!$ip) {
                   13961:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13962:             if (length($ip) == 4) { 
                   13963: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13964:             }
                   13965:         }
                   13966:         if ($ip) {
                   13967: 	    @hosts = get_hosts_from_ip($ip);
                   13968: 	    return $hosts[0];
                   13969:         }
                   13970:         return undef;
1.986     foxr     13971:     }
1.992     raeburn  13972: 
1.1074    raeburn  13973:     sub get_internet_names {
                   13974:         my ($lonid) = @_;
                   13975:         return if ($lonid eq '');
                   13976:         my ($idnref,$cached)=
                   13977:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13978:         if ($cached) {
                   13979:             return $idnref;
                   13980:         }
                   13981:         my $ip = &get_host_ip($lonid);
                   13982:         my @hosts = &get_hosts_from_ip($ip);
                   13983:         my %iphost = &get_iphost();
                   13984:         my (@idns,%seen);
                   13985:         foreach my $id (@hosts) {
                   13986:             my $dom = &host_domain($id);
                   13987:             my $prim_id = &domain($dom,'primary');
                   13988:             my $prim_ip = &get_host_ip($prim_id);
                   13989:             next if ($seen{$prim_ip});
                   13990:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13991:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13992:                     my $intdom = &internet_dom($id);
                   13993:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13994:                         push(@idns,$intdom);
                   13995:                     }
                   13996:                 }
                   13997:             }
                   13998:             $seen{$prim_ip} = 1;
                   13999:         }
1.1172.2.23  raeburn  14000:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14001:     }
                   14002: 
1.986     foxr     14003: }
                   14004: 
1.1079    raeburn  14005: sub all_loncaparevs {
1.1172.2.39  raeburn  14006:     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  14007: }
                   14008: 
1.1172.2.27  raeburn  14009: # ------------------------------------------------------- Read loncaparev table
                   14010: {
                   14011:     sub load_loncaparevs {
                   14012:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14013:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14014:                 while (my $configline=<$config>) {
                   14015:                     chomp($configline);
                   14016:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14017:                     $loncaparevs{$hostid}=$loncaparev;
                   14018:                 }
                   14019:                 close($config);
                   14020:             }
                   14021:         }
                   14022:     }
                   14023: }
                   14024: 
                   14025: # ----------------------------------------------------- Read serverhostID table
                   14026: {
                   14027:     sub load_serverhomeIDs {
                   14028:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14029:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14030:                 while (my $configline=<$config>) {
                   14031:                     chomp($configline);
                   14032:                     my ($name,$id)=split(/:/,$configline);
                   14033:                     $serverhomeIDs{$name}=$id;
                   14034:                 }
                   14035:                 close($config);
                   14036:             }
                   14037:         }
                   14038:     }
                   14039: }
                   14040: 
                   14041: 
1.862     albertel 14042: BEGIN {
                   14043: 
                   14044: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14045:     unless ($readit) {
                   14046: {
                   14047:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14048:     %perlvar = (%perlvar,%{$configvars});
                   14049: }
                   14050: 
                   14051: 
1.1       albertel 14052: # ------------------------------------------------------ Read spare server file
                   14053: {
1.1172.2.96  raeburn  14054:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14055: 
                   14056:     while (my $configline=<$config>) {
                   14057:        chomp($configline);
1.284     matthew  14058:        if ($configline) {
1.784     albertel 14059: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14060: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14061: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14062:        }
                   14063:     }
1.448     albertel 14064:     close($config);
1.1       albertel 14065: }
1.11      www      14066: # ------------------------------------------------------------ Read permissions
                   14067: {
1.1172.2.96  raeburn  14068:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14069: 
                   14070:     while (my $configline=<$config>) {
1.448     albertel 14071: 	chomp($configline);
                   14072: 	if ($configline) {
                   14073: 	    my ($role,$perm)=split(/ /,$configline);
                   14074: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14075: 	}
1.11      www      14076:     }
1.448     albertel 14077:     close($config);
1.11      www      14078: }
                   14079: 
                   14080: # -------------------------------------------- Read plain texts for permissions
                   14081: {
1.1172.2.96  raeburn  14082:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14083: 
                   14084:     while (my $configline=<$config>) {
1.448     albertel 14085: 	chomp($configline);
                   14086: 	if ($configline) {
1.742     raeburn  14087: 	    my ($short,@plain)=split(/:/,$configline);
                   14088:             %{$prp{$short}} = ();
                   14089: 	    if (@plain > 0) {
                   14090:                 $prp{$short}{'std'} = $plain[0];
                   14091:                 for (my $i=1; $i<@plain; $i++) {
                   14092:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14093:                 }
                   14094:             }
1.448     albertel 14095: 	}
1.135     www      14096:     }
1.448     albertel 14097:     close($config);
1.135     www      14098: }
                   14099: 
                   14100: # ---------------------------------------------------------- Read package table
                   14101: {
1.1172.2.96  raeburn  14102:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14103: 
                   14104:     while (my $configline=<$config>) {
1.483     albertel 14105: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14106: 	chomp($configline);
                   14107: 	my ($short,$plain)=split(/:/,$configline);
                   14108: 	my ($pack,$name)=split(/\&/,$short);
                   14109: 	if ($plain ne '') {
                   14110: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14111: 	    $packagetab{$short}=$plain; 
                   14112: 	}
1.11      www      14113:     }
1.448     albertel 14114:     close($config);
1.329     matthew  14115: }
                   14116: 
1.1172.2.27  raeburn  14117: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14118: 
1.1172.2.27  raeburn  14119: &load_loncaparevs();
                   14120: 
                   14121: # ------------------------------------------------------- Read serverhostID table
                   14122: 
                   14123: &load_serverhomeIDs();
1.1074    raeburn  14124: 
1.1172.2.27  raeburn  14125: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14126: {
                   14127:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14128:     if (-e $file) {
                   14129:         my $parser = HTML::LCParser->new($file);
                   14130:         while (my $token = $parser->get_token()) {
                   14131:             if ($token->[0] eq 'S') {
                   14132:                 my $item = $token->[1];
                   14133:                 my $name = $token->[2]{'name'};
                   14134:                 my $value = $token->[2]{'value'};
                   14135:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14136:                     my $release = $parser->get_text();
                   14137:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14138:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14139:                 }
                   14140:             }
                   14141:         }
                   14142:     }
1.1073    raeburn  14143: }
                   14144: 
1.1138    raeburn  14145: # ---------------------------------------------------------- Read managers table
                   14146: {
                   14147:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14148:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14149:             while (my $configline=<$config>) {
                   14150:                 chomp($configline);
                   14151:                 next if ($configline =~ /^\#/);
                   14152:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14153:                     $managerstab{$configline} = 1;
                   14154:                 }
                   14155:             }
                   14156:             close($config);
                   14157:         }
                   14158:     }
                   14159: }
                   14160: 
1.329     matthew  14161: # ------------- set up temporary directory
                   14162: {
1.1117    foxr     14163:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14164: 
1.11      www      14165: }
                   14166: 
1.1172.2.104  raeburn  14167: # ------------- set default texengine (domain default overrides this)
                   14168: {
                   14169:     $deftex = LONCAPA::texengine();
                   14170: }
                   14171: 
1.1172.2.114  raeburn  14172: # ------------- set default minimum length for passwords for internal auth users
                   14173: {
                   14174:     $passwdmin = LONCAPA::passwd_min();
                   14175: }
                   14176: 
1.794     albertel 14177: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14178: 				'compress_threshold'=> 20_000,
                   14179:  			        });
1.185     www      14180: 
1.281     www      14181: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14182: $dumpcount=0;
1.958     www      14183: $locknum=0;
1.22      www      14184: 
1.163     harris41 14185: &logtouch();
1.672     albertel 14186: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14187: $readit=1;
1.564     albertel 14188:     {
                   14189: 	use integer;
                   14190: 	my $test=(2**32)+1;
1.568     albertel 14191: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14192: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14193:     }
1.195     www      14194: }
1.1       albertel 14195: }
1.179     www      14196: 
1.1       albertel 14197: 1;
1.191     harris41 14198: __END__
                   14199: 
1.243     albertel 14200: =pod
                   14201: 
1.191     harris41 14202: =head1 NAME
                   14203: 
1.243     albertel 14204: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14205: 
                   14206: =head1 SYNOPSIS
                   14207: 
1.243     albertel 14208: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14209: 
                   14210:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14211: 
1.243     albertel 14212: Common parameters:
                   14213: 
                   14214: =over 4
                   14215: 
                   14216: =item *
                   14217: 
                   14218: $uname : an internal username (if $cname expecting a course Id specifically)
                   14219: 
                   14220: =item *
                   14221: 
                   14222: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14223: 
                   14224: =item *
                   14225: 
                   14226: $symb : a resource instance identifier
                   14227: 
                   14228: =item *
                   14229: 
                   14230: $namespace : the name of a .db file that contains the data needed or
                   14231: being set.
                   14232: 
                   14233: =back
                   14234: 
1.394     bowersj2 14235: =head1 OVERVIEW
1.191     harris41 14236: 
1.394     bowersj2 14237: lonnet provides subroutines which interact with the
                   14238: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14239: about classes, users, and resources.
1.243     albertel 14240: 
                   14241: For many of these objects you can also use this to store data about
                   14242: them or modify them in various ways.
1.191     harris41 14243: 
1.394     bowersj2 14244: =head2 Symbs
1.191     harris41 14245: 
1.394     bowersj2 14246: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14247: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14248: map, the resource number of the resource in the map, and the URL of
                   14249: the resource itself. The latter is somewhat redundant, but might help
                   14250: if maps change.
                   14251: 
                   14252: An example is
                   14253: 
                   14254:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14255: 
                   14256: The respective map entry is
                   14257: 
                   14258:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14259:   title="Problem 2">
                   14260:  </resource>
                   14261: 
                   14262: Symbs are used by the random number generator, as well as to store and
                   14263: restore data specific to a certain instance of for example a problem.
                   14264: 
                   14265: =head2 Storing And Retrieving Data
                   14266: 
                   14267: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14268: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14269: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14270: is is the non-critical message twin of cstore. These functions are for
                   14271: handlers to store a perl hash to a user's permanent data space in an
                   14272: easy manner, and to retrieve it again on another call. It is expected
                   14273: that a handler would use this once at the beginning to retrieve data,
                   14274: and then again once at the end to send only the new data back.
                   14275: 
                   14276: The data is stored in the user's data directory on the user's
                   14277: homeserver under the ID of the course.
                   14278: 
                   14279: The hash that is returned by restore will have all of the previous
                   14280: value for all of the elements of the hash.
                   14281: 
                   14282: Example:
                   14283: 
                   14284:  #creating a hash
                   14285:  my %hash;
                   14286:  $hash{'foo'}='bar';
                   14287: 
                   14288:  #storing it
                   14289:  &Apache::lonnet::cstore(\%hash);
                   14290: 
                   14291:  #changing a value
                   14292:  $hash{'foo'}='notbar';
                   14293: 
                   14294:  #adding a new value
                   14295:  $hash{'bar'}='foo';
                   14296:  &Apache::lonnet::cstore(\%hash);
                   14297: 
                   14298:  #retrieving the hash
                   14299:  my %history=&Apache::lonnet::restore();
                   14300: 
                   14301:  #print the hash
                   14302:  foreach my $key (sort(keys(%history))) {
                   14303:    print("\%history{$key} = $history{$key}");
                   14304:  }
                   14305: 
                   14306: Will print out:
1.191     harris41 14307: 
1.394     bowersj2 14308:  %history{1:foo} = bar
                   14309:  %history{1:keys} = foo:timestamp
                   14310:  %history{1:timestamp} = 990455579
                   14311:  %history{2:bar} = foo
                   14312:  %history{2:foo} = notbar
                   14313:  %history{2:keys} = foo:bar:timestamp
                   14314:  %history{2:timestamp} = 990455580
                   14315:  %history{bar} = foo
                   14316:  %history{foo} = notbar
                   14317:  %history{timestamp} = 990455580
                   14318:  %history{version} = 2
                   14319: 
                   14320: Note that the special hash entries C<keys>, C<version> and
                   14321: C<timestamp> were added to the hash. C<version> will be equal to the
                   14322: total number of versions of the data that have been stored. The
                   14323: C<timestamp> attribute will be the UNIX time the hash was
                   14324: stored. C<keys> is available in every historical section to list which
                   14325: keys were added or changed at a specific historical revision of a
                   14326: hash.
                   14327: 
                   14328: B<Warning>: do not store the hash that restore returns directly. This
                   14329: will cause a mess since it will restore the historical keys as if the
                   14330: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14331: 
1.394     bowersj2 14332: Calling convention:
1.191     harris41 14333: 
1.1172.2.27  raeburn  14334:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14335:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14336: 
1.394     bowersj2 14337: For more detailed information, see lonnet specific documentation.
1.191     harris41 14338: 
1.394     bowersj2 14339: =head1 RETURN MESSAGES
1.191     harris41 14340: 
1.394     bowersj2 14341: =over 4
1.191     harris41 14342: 
1.394     bowersj2 14343: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14344: 
1.394     bowersj2 14345: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14346: when the connection is brought back up
1.191     harris41 14347: 
1.394     bowersj2 14348: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14349: for later delivery
1.191     harris41 14350: 
1.967     bisitz   14351: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14352: 
1.394     bowersj2 14353: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14354: that was requested
1.191     harris41 14355: 
1.243     albertel 14356: =back
1.191     harris41 14357: 
1.243     albertel 14358: =head1 PUBLIC SUBROUTINES
1.191     harris41 14359: 
1.243     albertel 14360: =head2 Session Environment Functions
1.191     harris41 14361: 
1.243     albertel 14362: =over 4
1.191     harris41 14363: 
1.394     bowersj2 14364: =item * 
                   14365: X<appenv()>
1.949     raeburn  14366: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14367: the user envirnoment file, and will be restored for each access this
1.620     albertel 14368: user makes during this session, also modifies the %env for the current
1.949     raeburn  14369: process. Optional rolesarrayref - if defined contains a reference to an array
                   14370: of roles which are exempt from the restriction on modifying user.role entries 
                   14371: in the user's environment.db and in %env.    
1.191     harris41 14372: 
                   14373: =item *
1.394     bowersj2 14374: X<delenv()>
1.987     raeburn  14375: B<delenv($delthis,$regexp)>: removes all items from the session
                   14376: environment file that begin with $delthis. If the 
                   14377: optional second arg - $regexp - is true, $delthis is treated as a 
                   14378: regular expression, otherwise \Q$delthis\E is used. 
                   14379: The values are also deleted from the current processes %env.
1.191     harris41 14380: 
1.795     albertel 14381: =item * get_env_multiple($name) 
                   14382: 
                   14383: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14384: values may be defined and end up as an array ref.
                   14385: 
                   14386: returns an array of values
                   14387: 
1.243     albertel 14388: =back
                   14389: 
                   14390: =head2 User Information
1.191     harris41 14391: 
1.243     albertel 14392: =over 4
1.191     harris41 14393: 
                   14394: =item *
1.394     bowersj2 14395: X<queryauthenticate()>
                   14396: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14397: authentication scheme
                   14398: 
                   14399: =item *
1.394     bowersj2 14400: X<authenticate()>
1.1073    raeburn  14401: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14402: authenticate user from domain's lib servers (first use the current
                   14403: one). C<$upass> should be the users password.
1.1073    raeburn  14404: $checkdefauth is optional (value is 1 if a check should be made to
                   14405:    authenticate user using default authentication method, and allow
                   14406:    account creation if username does not have account in the domain).
                   14407: $clientcancheckhost is optional (value is 1 if checking whether the
                   14408:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14409: 
                   14410: =item *
1.394     bowersj2 14411: X<homeserver()>
                   14412: B<homeserver($uname,$udom)>: find the server which has
                   14413: the user's directory and files (there must be only one), this caches
                   14414: the answer, and also caches if there is a borken connection.
1.191     harris41 14415: 
                   14416: =item *
1.394     bowersj2 14417: X<idget()>
                   14418: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14419: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14420: username, and only 1 username per ID in a specific domain) (returns
                   14421: hash: id=>name,id=>name)
1.191     harris41 14422: 
                   14423: =item *
1.394     bowersj2 14424: X<idrget()>
                   14425: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14426: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14427: 
                   14428: =item *
1.394     bowersj2 14429: X<idput()>
                   14430: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14431: 
                   14432: =item *
1.394     bowersj2 14433: X<rolesinit()>
1.1169    droeschl 14434: B<rolesinit($udom,$username)>: get user privileges.
                   14435: returns user role, first access and timer interval hashes
1.243     albertel 14436: 
                   14437: =item *
1.1171    droeschl 14438: X<privileged()>
                   14439: B<privileged($username,$domain)>: returns a true if user has a
                   14440: privileged and active role (i.e. su or dc), false otherwise.
                   14441: 
                   14442: =item *
1.551     albertel 14443: X<getsection()>
                   14444: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14445: course $cname, return section name/number or '' for "not in course"
                   14446: and '-1' for "no section"
                   14447: 
                   14448: =item *
1.394     bowersj2 14449: X<userenvironment()>
                   14450: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14451: passed in @what from the requested user's environment, returns a hash
                   14452: 
1.858     raeburn  14453: =item * 
                   14454: X<userlog_query()>
1.859     albertel 14455: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14456: activity.log file. %filters defines filters applied when parsing the
                   14457: log file. These can be start or end timestamps, or the type of action
                   14458: - log to look for Login or Logout events, check for Checkin or
                   14459: Checkout, role for role selection. The response is in the form
                   14460: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14461: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14462: 
1.243     albertel 14463: =back
                   14464: 
                   14465: =head2 User Roles
                   14466: 
                   14467: =over 4
                   14468: 
                   14469: =item *
                   14470: 
1.1172.2.65  raeburn  14471: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14472: returns codes for allowed actions.
                   14473: 
                   14474: The first argument is required, all others are optional.
                   14475: 
                   14476: $priv is the privilege being checked.
                   14477: $uri contains additional information about what is being checked for access (e.g.,
                   14478: URL, course ID etc.).
                   14479: $symb is the unique resource instance identifier in a course; if needed,
                   14480: but not provided, it will be retrieved via a call to &symbread().
                   14481: $role is the role for which a priv is being checked (only used if priv is evb).
                   14482: $clientip is the user's IP address (only used when checking for access to portfolio
                   14483: files).
                   14484: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14485: prevents recursive calls to &allowed.
                   14486: 
1.243     albertel 14487:  F: full access
                   14488:  U,I,K: authentication modes (cxx only)
                   14489:  '': forbidden
                   14490:  1: user needs to choose course
                   14491:  2: browse allowed
1.766     albertel 14492:  A: passphrase authentication needed
1.1172.2.65  raeburn  14493:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14494: 
                   14495: =item *
                   14496: 
1.1172.2.13  raeburn  14497: constructaccess($url,$setpriv) : check for access to construction space URL
                   14498: 
                   14499: See if the owner domain and name in the URL match those in the
                   14500: expected environment.  If so, return three element list
                   14501: ($ownername,$ownerdomain,$ownerhome).
                   14502: 
                   14503: Otherwise return the null string.
                   14504: 
                   14505: If second argument 'setpriv' is true, it assigns the privileges,
                   14506: and returns the same three element list, unless the owner has
                   14507: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14508: in which case the null string is returned.
                   14509: 
                   14510: =item *
                   14511: 
1.1172.2.84  raeburn  14512: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14513: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14514: for system, domain, and course level. $uname and $udom are optional (current
                   14515: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14516: 
                   14517: =item *
                   14518: 
1.988     raeburn  14519: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14520: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14521: $type is Course (default) or Community.
1.988     raeburn  14522: If $forcedefault evaluates to true, text returned will be default 
                   14523: text for $type. Otherwise, if this is a course, the text returned 
                   14524: will be a custom name for the role (if defined in the course's 
                   14525: environment).  If no custom name is defined the default is returned.
                   14526:    
1.832     raeburn  14527: =item *
                   14528: 
1.1172.2.23  raeburn  14529: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14530: All arguments are optional. Returns a hash of a roles, either for
                   14531: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14532: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14533: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14534: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14535: For each key, value is set to colon-separated start and end times for
                   14536: the role.  If no username and domain are specified, will default to
1.934     raeburn  14537: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14538: of role statuses (active, future or previous), roles 
                   14539: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14540: to restrict the list of roles reported. If no array ref is 
                   14541: provided for types, will default to return only active roles.
1.834     albertel 14542: 
1.1172.2.13  raeburn  14543: =item *
                   14544: 
                   14545: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14546: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14547: 
                   14548: Additional optional arguments are: $type (if role checking is to be restricted
                   14549: to certain user status types -- previous (expired roles), active (currently
                   14550: available roles) or future (roles available in the future), and
                   14551: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14552: have active Domain Coordinator role in course's domain or in additional
                   14553: domains (specified in 'Domains to check for privileged users' in course
                   14554: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14555: 
                   14556: =item *
                   14557: 
                   14558: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14559: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14560: $possdomains and $possroles are optional array refs -- to domains to check and
                   14561: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14562: users' roles.db to check for a dc or su role in any domain. This can be
                   14563: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14564: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14565: this then allows &privileged_by_domain() to be used, which caches the identity
                   14566: of privileged users, eliminating the need for repeated calls to &dump().
                   14567: 
                   14568: =item *
                   14569: 
                   14570: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14571: where the outer hash keys are domains specified in the $possdomains array ref,
                   14572: next inner hash keys are privileged roles specified in the $roles array ref,
                   14573: and the innermost hash contains key = value pairs for username:domain = end:start
                   14574: for active or future "privileged" users with that role in that domain. To avoid
                   14575: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14576: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14577: 
1.243     albertel 14578: =back
                   14579: 
                   14580: =head2 User Modification
                   14581: 
                   14582: =over 4
                   14583: 
                   14584: =item *
                   14585: 
1.957     raeburn  14586: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14587: user for the level given by URL.  Optional start and end dates (leave empty
                   14588: string or zero for "no date")
1.191     harris41 14589: 
                   14590: =item *
                   14591: 
1.243     albertel 14592: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14593: change a users, password, possible return values are: ok,
                   14594: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14595: refused
1.191     harris41 14596: 
                   14597: =item *
                   14598: 
1.243     albertel 14599: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14600: 
                   14601: =item *
                   14602: 
1.1058    raeburn  14603: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14604:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14605: 
                   14606: will update user information (firstname,middlename,lastname,generation,
                   14607: permanentemail), and if forceid is true, student/employee ID also.
                   14608: A user's institutional affiliation(s) can also be updated.
                   14609: User information fields will not be overwritten with empty entries 
                   14610: unless the field is included in the $candelete array reference.
                   14611: This array is included when a single user is modified via "Manage Users",
                   14612: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14613: 
                   14614: =item *
                   14615: 
1.286     matthew  14616: modifystudent
                   14617: 
1.957     raeburn  14618: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14619: The course id is resolved based on the current user's environment.  
                   14620: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14621: associated with a course.
                   14622: 
1.297     matthew  14623: This call is essentially a wrapper for lonnet::modifyuser and
                   14624: lonnet::modify_student_enrollment
1.286     matthew  14625: 
                   14626: Inputs: 
                   14627: 
                   14628: =over 4
                   14629: 
1.957     raeburn  14630: =item B<$udom> Student's loncapa domain
1.286     matthew  14631: 
1.957     raeburn  14632: =item B<$uname> Student's loncapa login name
1.286     matthew  14633: 
1.964     bisitz   14634: =item B<$uid> Student/Employee ID
1.286     matthew  14635: 
1.957     raeburn  14636: =item B<$umode> Student's authentication mode
1.286     matthew  14637: 
1.957     raeburn  14638: =item B<$upass> Student's password
1.286     matthew  14639: 
1.957     raeburn  14640: =item B<$first> Student's first name
1.286     matthew  14641: 
1.957     raeburn  14642: =item B<$middle> Student's middle name
1.286     matthew  14643: 
1.957     raeburn  14644: =item B<$last> Student's last name
1.286     matthew  14645: 
1.957     raeburn  14646: =item B<$gene> Student's generation
1.286     matthew  14647: 
1.957     raeburn  14648: =item B<$usec> Student's section in course
1.286     matthew  14649: 
                   14650: =item B<$end> Unix time of the roles expiration
                   14651: 
                   14652: =item B<$start> Unix time of the roles start date
                   14653: 
                   14654: =item B<$forceid> If defined, allow $uid to be changed
                   14655: 
                   14656: =item B<$desiredhome> server to use as home server for student
                   14657: 
1.957     raeburn  14658: =item B<$email> Student's permanent e-mail address
                   14659: 
                   14660: =item B<$type> Type of enrollment (auto or manual)
                   14661: 
1.963     raeburn  14662: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14663: 
                   14664: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14665: 
1.963     raeburn  14666: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14667: 
1.963     raeburn  14668: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14669: 
1.1172.2.19  raeburn  14670: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14671: 
                   14672: =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  14673: 
1.286     matthew  14674: =back
1.297     matthew  14675: 
                   14676: =item *
                   14677: 
                   14678: modify_student_enrollment
                   14679: 
1.1172.2.31  raeburn  14680: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14681: 'role.request.course' must be defined for this function to proceed.
                   14682: 
                   14683: Inputs:
                   14684: 
                   14685: =over 4
                   14686: 
1.1172.2.31  raeburn  14687: =item $udom, student's domain
1.297     matthew  14688: 
1.1172.2.31  raeburn  14689: =item $uname, student's name
1.297     matthew  14690: 
1.1172.2.31  raeburn  14691: =item $uid, student's user id
1.297     matthew  14692: 
1.1172.2.31  raeburn  14693: =item $first, student's first name
1.297     matthew  14694: 
                   14695: =item $middle
                   14696: 
                   14697: =item $last
                   14698: 
                   14699: =item $gene
                   14700: 
                   14701: =item $usec
                   14702: 
                   14703: =item $end
                   14704: 
                   14705: =item $start
                   14706: 
1.957     raeburn  14707: =item $type
                   14708: 
                   14709: =item $locktype
                   14710: 
                   14711: =item $cid
                   14712: 
                   14713: =item $selfenroll
                   14714: 
                   14715: =item $context
                   14716: 
1.1172.2.19  raeburn  14717: =item $credits, number of credits student will earn from this class
                   14718: 
1.1172.2.76  raeburn  14719: =item $instsec, institutional course section code for student
                   14720: 
1.297     matthew  14721: =back
                   14722: 
1.191     harris41 14723: 
                   14724: =item *
                   14725: 
1.243     albertel 14726: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14727: custom role; give a custom role to a user for the level given by URL.  Specify
                   14728: name and domain of role author, and role name
1.191     harris41 14729: 
                   14730: =item *
                   14731: 
1.243     albertel 14732: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14733: 
                   14734: =item *
                   14735: 
1.243     albertel 14736: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14737: 
                   14738: =back
                   14739: 
                   14740: =head2 Course Infomation
                   14741: 
                   14742: =over 4
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.1118    foxr     14746: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14747: specified course id, including all environment settings for the
                   14748: course, the description of the course will be in the hash under the
                   14749: key 'description'
1.191     harris41 14750: 
1.1118    foxr     14751: $options is an optional parameter that if supplied is a hash reference that controls
                   14752: what how this function works.  It has the following key/values:
                   14753: 
                   14754: =over 4
                   14755: 
                   14756: =item freshen_cache
                   14757: 
                   14758: If defined, and the environment cache for the course is valid, it is 
                   14759: returned in the returned hash.
                   14760: 
                   14761: =item one_time
                   14762: 
                   14763: If defined, the last cache time is set to _now_
                   14764: 
                   14765: =item user
                   14766: 
                   14767: If defined, the supplied username is used instead of the current user.
                   14768: 
                   14769: 
                   14770: =back
                   14771: 
1.191     harris41 14772: =item *
                   14773: 
1.624     albertel 14774: resdata($name,$domain,$type,@which) : request for current parameter
                   14775: setting for a specific $type, where $type is either 'course' or 'user',
                   14776: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14777: answers for 10 minutes.
1.243     albertel 14778: 
1.877     foxr     14779: =item *
                   14780: 
                   14781: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14782: data base, returning a hash that is keyed by the resource name and has
                   14783: values that are the resource value.  I believe that the timestamps and
                   14784: versions are also returned.
                   14785: 
1.1172.2.31  raeburn  14786: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14787: supplemental content area. This routine caches the number of files for
                   14788: 10 minutes.
                   14789: 
1.243     albertel 14790: =back
                   14791: 
                   14792: =head2 Course Modification
                   14793: 
                   14794: =over 4
1.191     harris41 14795: 
                   14796: =item *
                   14797: 
1.243     albertel 14798: writecoursepref($courseid,%prefs) : write preferences (environment
                   14799: database) for a course
1.191     harris41 14800: 
                   14801: =item *
                   14802: 
1.1011    raeburn  14803: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14804: 
                   14805: =item *
                   14806: 
1.1038    raeburn  14807: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14808: 
1.1167    droeschl 14809: =item *
                   14810: 
                   14811: is_course($courseid), is_course($cdom, $cnum)
                   14812: 
                   14813: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14814: two component version $cdom, $cnum. It checks if the specified course exists.
                   14815: 
                   14816: Returns:
                   14817:     undef if the course doesn't exist, otherwise
                   14818:     in scalar context the combined courseid.
                   14819:     in list context the two components of the course identifier, domain and 
                   14820:     courseid.    
                   14821: 
1.243     albertel 14822: =back
                   14823: 
1.1172.2.109  raeburn  14824: =head2 Bubblesheet Configuration
                   14825: 
                   14826: =over 4
                   14827: 
                   14828: =item *
                   14829: 
                   14830: get_scantron_config($which)
                   14831: 
                   14832: $which - the name of the configuration to parse from the file.
                   14833: 
                   14834: Parses and returns the bubblesheet configuration line selected as a
                   14835: hash of configuration file fields.
                   14836: 
                   14837: 
                   14838: Returns:
                   14839:     If the named configuration is not in the file, an empty
                   14840:     hash is returned.
                   14841: 
                   14842:     a hash with the fields
                   14843:       name         - internal name for the this configuration setup
                   14844:       description  - text to display to operator that describes this config
                   14845:       CODElocation - if 0 or the string 'none'
                   14846:                           - no CODE exists for this config
                   14847:                      if -1 || the string 'letter'
                   14848:                           - a CODE exists for this config and is
                   14849:                             a string of letters
                   14850:                      Unsupported value (but planned for future support)
                   14851:                           if a positive integer
                   14852:                                - The CODE exists as the first n items from
                   14853:                                  the question section of the form
                   14854:                           if the string 'number'
                   14855:                                - The CODE exists for this config and is
                   14856:                                  a string of numbers
                   14857:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14858:                      the CODE starts
                   14859:       CODElength  - length of the CODE
                   14860:       IDstart     - column where the student/employee ID starts
                   14861:       IDlength    - length of the student/employee ID info
                   14862:       Qstart      - column where the information from the bubbled
                   14863:                     'questions' start
                   14864:       Qlength     - number of columns comprising a single bubble line from
                   14865:                     the sheet. (usually either 1 or 10)
                   14866:       Qon         - either a single character representing the character used
                   14867:                     to signal a bubble was chosen in the positional setup, or
                   14868:                     the string 'letter' if the letter of the chosen bubble is
                   14869:                     in the final, or 'number' if a number representing the
                   14870:                     chosen bubble is in the file (1->A 0->J)
                   14871:       Qoff        - the character used to represent that a bubble was
                   14872:                     left blank
                   14873:       PaperID     - if the scanning process generates a unique number for each
                   14874:                     sheet scanned the column that this ID number starts in
                   14875:       PaperIDlength - number of columns that comprise the unique ID number
                   14876:                       for the sheet of paper
                   14877:       FirstName   - column that the first name starts in
                   14878:       FirstNameLength - number of columns that the first name spans
                   14879:       LastName    - column that the last name starts in
                   14880:       LastNameLength - number of columns that the last name spans
                   14881:       BubblesPerRow - number of bubbles available in each row used to
                   14882:                       bubble an answer. (If not specified, 10 assumed).
                   14883: 
                   14884: 
                   14885: =item *
                   14886: 
                   14887: get_scantronformat_file($cdom)
                   14888: 
                   14889: $cdom - the course's domain (optional); if not supplied, uses
                   14890: domain for current $env{'request.course.id'}.
                   14891: 
                   14892: Returns an array containing lines from the scantron format file for
                   14893: the domain of the course.
                   14894: 
                   14895: If a url for a custom.tab file is listed in domain's configuration.db,
                   14896: lines are from this file.
                   14897: 
                   14898: Otherwise, if a default.tab has been published in RES space by the
                   14899: domainconfig user, lines are from this file.
                   14900: 
                   14901: Otherwise, fall back to getting lines from the legacy file on the
                   14902: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14903: 
                   14904: =back
                   14905: 
1.243     albertel 14906: =head2 Resource Subroutines
                   14907: 
                   14908: =over 4
1.191     harris41 14909: 
                   14910: =item *
                   14911: 
1.243     albertel 14912: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
1.243     albertel 14916: repcopy($filename) : subscribes to the requested file, and attempts to
                   14917: replicate from the owning library server, Might return
1.607     raeburn  14918: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14919: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14920: resource. Expects the local filesystem pathname
                   14921: (/home/httpd/html/res/....)
                   14922: 
                   14923: =back
                   14924: 
                   14925: =head2 Resource Information
                   14926: 
                   14927: =over 4
1.191     harris41 14928: 
                   14929: =item *
                   14930: 
1.1172.2.28  raeburn  14931: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14932: and returns the value of a variety of different possible values,
                   14933: $varname should be a request string, and the other parameters can be
                   14934: used to specify who and what one is asking about. Ordinarily, $cid 
                   14935: does not need to be specified, as it is retrived from 
                   14936: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14937: within lonuserstate::loadmap() when initializing a course, before
                   14938: $env{'request.course.id'} has been set, so it needs to be provided
                   14939: in that one case.
1.243     albertel 14940: 
                   14941: Possible values for $varname are environment.lastname (or other item
                   14942: from the envirnment hash), user.name (or someother aspect about the
                   14943: user), resource.0.maxtries (or some other part and parameter of a
                   14944: resource)
1.204     albertel 14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: directcondval($number) : get current value of a condition; reads from a state
                   14949: string
1.204     albertel 14950: 
                   14951: =item *
                   14952: 
1.243     albertel 14953: condval($condidx) : value of condition index based on state
1.204     albertel 14954: 
                   14955: =item *
                   14956: 
1.243     albertel 14957: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14958: resource's metadata, $what should be either a specific key, or either
                   14959: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14960: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14961: 
                   14962: this function automatically caches all requests
1.191     harris41 14963: 
                   14964: =item *
                   14965: 
1.243     albertel 14966: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14967: network of library servers; returns file handle of where SQL and regex results
                   14968: will be stored for query
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.1172.2.66  raeburn  14972: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14973: return symbolic list entry (all arguments optional).
                   14974: 
                   14975: Args: filename is the filename (including path) for the file for which a symb
                   14976: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14977: to check access status if more than one resource was found in the bighash
                   14978: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14979: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14980: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14981: cause possible symbs to be checked to determine if they are subject to content
                   14982: blocking, if so they will not be included as possible symbs; possibles is a
                   14983: ref to a hash, which, as a side effect, will be populated with all possible
                   14984: symbs (content blocking not tested).
                   14985: 
1.243     albertel 14986: returns the data handle
1.191     harris41 14987: 
                   14988: =item *
                   14989: 
1.1172.2.17  raeburn  14990: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14991: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14992: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14993: on failure, user must be in a course, as it assumes the existence of
                   14994: the course initial hash, and uses $env('request.course.id'}.  The third
                   14995: arg is an optional reference to a scalar.  If this arg is passed in the
                   14996: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14997: encrypted; otherwise it will be null.
1.243     albertel 14998: 
1.191     harris41 14999: =item *
                   15000: 
1.243     albertel 15001: symbclean($symb) : removes versions numbers from a symb, returns the
                   15002: cleaned symb
1.191     harris41 15003: 
                   15004: =item *
                   15005: 
1.243     albertel 15006: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15007: course map, user must be in a course for it to work.
1.191     harris41 15008: 
                   15009: =item *
                   15010: 
1.243     albertel 15011: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15012: 
                   15013: =item *
                   15014: 
1.243     albertel 15015: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15016: a random seed, all arguments are optional, if they aren't sent it uses the
                   15017: environment to derive them. Note: if symb isn't sent and it can't get one
                   15018: from &symbread it will use the current time as its return value
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.243     albertel 15022: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15023: unfakeable, receipt
1.191     harris41 15024: 
                   15025: =item *
                   15026: 
1.620     albertel 15027: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15028: 
                   15029: =item *
                   15030: 
1.243     albertel 15031: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15032: 
                   15033: =item *
                   15034: 
1.243     albertel 15035: 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 15036: 
                   15037: =item *
                   15038: 
1.243     albertel 15039: 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 15040: 
                   15041: =item *
                   15042: 
1.243     albertel 15043: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.243     albertel 15047: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15048: forcing spreadsheet to reevaluate the resource scores next time.
                   15049: 
1.1172.2.13  raeburn  15050: =item *
                   15051: 
                   15052: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15053: when viewing in course context.
                   15054: 
                   15055:  input: six args -- filename (decluttered), course number, course domain,
                   15056:                     url, symb (if registered) and group (if this is a
                   15057:                     group item -- e.g., bulletin board, group page etc.).
                   15058: 
                   15059:  output: array of five scalars --
                   15060:          $cfile -- url for file editing if editable on current server
                   15061:          $home -- homeserver of resource (i.e., for author if published,
                   15062:                                           or course if uploaded.).
                   15063:          $switchserver --  1 if server switch will be needed.
                   15064:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15065:          $forceview -- 1 if icon/link should be to go to view mode
                   15066: 
                   15067: =item *
                   15068: 
                   15069: is_course_upload($file,$cnum,$cdom)
                   15070: 
                   15071: Used in course context to determine if current file was uploaded to
                   15072: the course (i.e., would be found in /userfiles/docs on the course's
                   15073: homeserver.
                   15074: 
                   15075:   input: 3 args -- filename (decluttered), course number and course domain.
                   15076:   output: boolean -- 1 if file was uploaded.
                   15077: 
1.243     albertel 15078: =back
                   15079: 
                   15080: =head2 Storing/Retreiving Data
                   15081: 
                   15082: =over 4
1.191     harris41 15083: 
                   15084: =item *
                   15085: 
1.1172.2.64  raeburn  15086: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15087: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15088: the remaining args aren't required and if they aren't passed or are '' they will
                   15089: be derived from the env (with the exception of $laststore, which is an
                   15090: optional arg used when a user's submission is stored in grading).
                   15091: $laststore is $version=$timestamp, where $version is the most recent version
                   15092: number retrieved for the corresponding $symb in the $namespace db file, and
                   15093: $timestamp is the timestamp for that transaction (UNIX time).
                   15094: $laststore is currently only passed when cstore() is called by
                   15095: structuretags::finalize_storage().
1.191     harris41 15096: 
                   15097: =item *
                   15098: 
1.1172.2.64  raeburn  15099: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15100: but uses critical subroutine
1.191     harris41 15101: 
                   15102: =item *
                   15103: 
1.243     albertel 15104: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15105: all args are optional
1.191     harris41 15106: 
                   15107: =item *
                   15108: 
1.717     albertel 15109: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15110: dumps the complete (or key matching regexp) namespace into a hash
                   15111: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15112: normally &store()ed into
                   15113: 
                   15114: $range should be either an integer '100' (give me the first 100
                   15115:                                            matching records)
                   15116:               or be  two integers sperated by a - with no spaces
                   15117:                  '30-50' (give me the 30th through the 50th matching
                   15118:                           records)
                   15119: 
                   15120: 
                   15121: =item *
                   15122: 
1.1172.2.59  raeburn  15123: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15124: replaces a &store() version of data with a replacement set of data
                   15125: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15126: reference. If $tolog is true, the transaction is logged in the courselog
                   15127: with an action=PUTSTORE.
1.717     albertel 15128: 
                   15129: =item *
                   15130: 
1.243     albertel 15131: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15132: works very similar to store/cstore, but all data is stored in a
                   15133: temporary location and can be reset using tmpreset, $storehash should
                   15134: be a hash reference, returns nothing on success
1.191     harris41 15135: 
                   15136: =item *
                   15137: 
1.243     albertel 15138: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15139: similar to restore, but all data is stored in a temporary location and
                   15140: can be reset using tmpreset. Returns a hash of values on success,
                   15141: error string otherwise.
1.191     harris41 15142: 
                   15143: =item *
                   15144: 
1.243     albertel 15145: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15146: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.243     albertel 15150: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15151: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15152: 
                   15153: =item *
                   15154: 
1.243     albertel 15155: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15156: namesp ($udom and $uname are optional)
1.191     harris41 15157: 
                   15158: =item *
                   15159: 
1.702     albertel 15160: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15161: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15162: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15163: 
1.702     albertel 15164: $range should be either an integer '100' (give me the first 100
                   15165:                                            matching records)
                   15166:               or be  two integers sperated by a - with no spaces
                   15167:                  '30-50' (give me the 30th through the 50th matching
                   15168:                           records)
1.449     matthew  15169: =item *
                   15170: 
                   15171: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15172: $store can be a scalar, an array reference, or if the amount to be 
                   15173: incremented is > 1, a hash reference.
                   15174: 
                   15175: ($udom and $uname are optional)
1.191     harris41 15176: 
                   15177: =item *
                   15178: 
1.243     albertel 15179: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15180: ($udom and $uname are optional)
1.191     harris41 15181: 
                   15182: =item *
                   15183: 
1.243     albertel 15184: cput($namespace,$storehash,$udom,$uname) : critical put
                   15185: ($udom and $uname are optional)
1.191     harris41 15186: 
                   15187: =item *
                   15188: 
1.748     albertel 15189: newput($namespace,$storehash,$udom,$uname) :
                   15190: 
                   15191: Attempts to store the items in the $storehash, but only if they don't
                   15192: currently exist, if this succeeds you can be certain that you have 
                   15193: successfully created a new key value pair in the $namespace db.
                   15194: 
                   15195: 
                   15196: Args:
                   15197:  $namespace: name of database to store values to
                   15198:  $storehash: hashref to store to the db
                   15199:  $udom: (optional) domain of user containing the db
                   15200:  $uname: (optional) name of user caontaining the db
                   15201: 
                   15202: Returns:
                   15203:  'ok' -> succeeded in storing all keys of $storehash
                   15204:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15205:                         least <key> already existed in the db (other
                   15206:                         requested keys may also already exist)
1.967     bisitz   15207:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15208:  'con_lost' -> unable to contact request server
                   15209:  'refused' -> action was not allowed by remote machine
                   15210: 
                   15211: 
                   15212: =item *
                   15213: 
1.243     albertel 15214: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15215: reference filled in from namesp (encrypts the return communication)
                   15216: ($udom and $uname are optional)
1.191     harris41 15217: 
                   15218: =item *
                   15219: 
1.243     albertel 15220: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15221: critical subroutine
                   15222: 
1.806     raeburn  15223: =item *
                   15224: 
1.860     raeburn  15225: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15226: array reference filled in from namespace found in domain level on either
                   15227: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15228: 
                   15229: =item *
                   15230: 
1.860     raeburn  15231: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15232: domain level either on specified domain server ($uhome) or primary domain 
                   15233: server ($udom and $uhome are optional)
1.806     raeburn  15234: 
1.943     raeburn  15235: =item * 
                   15236: 
1.1172.2.35  raeburn  15237: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15238: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15239: the target domain.
                   15240: 
                   15241: May also include additional key => value pairs for the following groups:
                   15242: 
                   15243: =over
                   15244: 
                   15245: =item
                   15246: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15247: 
                   15248: =over
                   15249: 
                   15250: =item defaultquota, authorquota
                   15251: 
                   15252: =back
                   15253: 
                   15254: =item
                   15255: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15256: portfolio for users).
                   15257: 
                   15258: =over
                   15259: 
                   15260: =item
                   15261: aboutme, blog, webdav, portfolio
                   15262: 
                   15263: =back
                   15264: 
                   15265: =item
                   15266: requestcourses: ability to request courses, and how requests are processed.
                   15267: 
                   15268: =over
                   15269: 
                   15270: =item
1.1172.2.37  raeburn  15271: official, unofficial, community, textbook
1.1172.2.35  raeburn  15272: 
                   15273: =back
                   15274: 
                   15275: =item
                   15276: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15277: 
                   15278: =over
                   15279: 
                   15280: =item
1.1172.2.44  raeburn  15281: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15282: 
                   15283: =back
                   15284: 
                   15285: =item
                   15286: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15287: for course's uploaded content.
                   15288: 
                   15289: =over
                   15290: 
                   15291: =item
1.1172.2.68  raeburn  15292: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15293: communityquota, textbookquota
1.1172.2.35  raeburn  15294: 
                   15295: =back
                   15296: 
                   15297: =item
                   15298: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15299: on your servers.
                   15300: 
                   15301: =over
                   15302: 
                   15303: =item
                   15304: remotesessions, hostedsessions
                   15305: 
                   15306: =back
                   15307: 
                   15308: =back
                   15309: 
                   15310: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15311: utility to create a configuration.db file on a domain's primary library server
                   15312: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15313: -- corresponding values are authentication type (internal, krb4, krb5,
                   15314: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15315: will be available. Values are retrieved from cache (if current), unless the
                   15316: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15317: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15318: 
                   15319: Typical usage:
1.943     raeburn  15320: 
1.1172.2.35  raeburn  15321: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15322: 
1.243     albertel 15323: =back
                   15324: 
                   15325: =head2 Network Status Functions
                   15326: 
                   15327: =over 4
1.191     harris41 15328: 
                   15329: =item *
                   15330: 
1.1137    raeburn  15331: dirlist() : return directory list based on URI (first arg).
                   15332: 
                   15333: Inputs: 1 required, 5 optional.
                   15334: 
                   15335: =over
                   15336: 
                   15337: =item 
                   15338: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15339: 
                   15340: =item
                   15341: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15342: 
                   15343: =item
                   15344: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15345: 
                   15346: =item
                   15347: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15348: 
                   15349: =item
                   15350: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15351: 
                   15352: =item 
                   15353: $alternateRoot - path to prepend in place of path from $uri.
                   15354: 
                   15355: =back
                   15356: 
                   15357: Returns: Array of up to two items.
                   15358: 
                   15359: =over
                   15360: 
                   15361: a reference to an array of files/subdirectories
                   15362: 
                   15363: =over
                   15364: 
                   15365: Each element in the array of files/subdirectories is a & separated list of
                   15366: item name and the result of running stat on the item.  If dirlist was requested
                   15367: for a file instead of a directory, the item name will be ''. For a directory 
                   15368: listing, if the item is a metadata file, the element will end &N&M 
                   15369: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15370: default copyright set (1).  
                   15371: 
                   15372: =back
                   15373: 
                   15374: a scalar containing error condition (if encountered).
                   15375: 
                   15376: =over
                   15377: 
                   15378: =item 
                   15379: no_host (no homeserver identified for $username:$domain).
                   15380: 
                   15381: =item 
                   15382: no_such_host (server contacted for listing not identified as valid host).
                   15383: 
                   15384: =item 
                   15385: con_lost (connection to remote server failed).
                   15386: 
                   15387: =item 
                   15388: refused (invalid $username:$domain received on lond side).
                   15389: 
                   15390: =item 
                   15391: no_such_dir (directory at specified path on lond side does not exist). 
                   15392: 
                   15393: =item 
                   15394: empty (directory at specified path on lond side is empty).
                   15395: 
                   15396: =over
                   15397: 
                   15398: This is currently not encountered because the &ls3, &ls2, 
                   15399: &ls (_handler) routines on the lond side do not filter out
                   15400: . and .. from a directory listing. 
                   15401: 
                   15402: =back
                   15403: 
                   15404: =back
                   15405: 
                   15406: =back
1.191     harris41 15407: 
                   15408: =item *
                   15409: 
1.243     albertel 15410: spareserver() : find server with least workload from spare.tab
                   15411: 
1.986     foxr     15412: 
                   15413: =item *
                   15414: 
                   15415: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15416: if there is no corresponding loncapa host.
                   15417: 
1.243     albertel 15418: =back
                   15419: 
1.986     foxr     15420: 
1.243     albertel 15421: =head2 Apache Request
                   15422: 
                   15423: =over 4
1.191     harris41 15424: 
                   15425: =item *
                   15426: 
1.243     albertel 15427: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15428: localhost, posts hash
                   15429: 
                   15430: =back
                   15431: 
                   15432: =head2 Data to String to Data
                   15433: 
                   15434: =over 4
1.191     harris41 15435: 
                   15436: =item *
                   15437: 
1.243     albertel 15438: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15439: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15440: 
                   15441: =item *
                   15442: 
1.243     albertel 15443: hashref2str($hashref) : convert a hashref into a string complete with
                   15444: escaping and '=' and '&' separators, supports elements that are
                   15445: arrayrefs and hashrefs
1.191     harris41 15446: 
                   15447: =item *
                   15448: 
1.243     albertel 15449: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15450: with escaping and '&' separators, supports elements that are arrayrefs
                   15451: and hashrefs
1.191     harris41 15452: 
                   15453: =item *
                   15454: 
1.243     albertel 15455: str2hash($string) : convert string to hash using unescaping and
                   15456: splitting on '=' and '&', supports elements that are arrayrefs and
                   15457: hashrefs
1.191     harris41 15458: 
                   15459: =item *
                   15460: 
1.243     albertel 15461: str2array($string) : convert string to hash using unescaping and
                   15462: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15463: 
                   15464: =back
                   15465: 
                   15466: =head2 Logging Routines
                   15467: 
                   15468: 
                   15469: These routines allow one to make log messages in the lonnet.log and
                   15470: lonnet.perm logfiles.
1.191     harris41 15471: 
1.1119    foxr     15472: =over 4
                   15473: 
1.191     harris41 15474: =item *
                   15475: 
1.243     albertel 15476: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15477: 
                   15478: =item *
                   15479: 
1.243     albertel 15480: logthis() : append message to the normal lonnet.log file, it gets
                   15481: preiodically rolled over and deleted.
1.191     harris41 15482: 
                   15483: =item *
                   15484: 
1.243     albertel 15485: logperm() : append a permanent message to lonnet.perm.log, this log
                   15486: file never gets deleted by any automated portion of the system, only
                   15487: messages of critical importance should go in here.
                   15488: 
1.1119    foxr     15489: 
1.243     albertel 15490: =back
                   15491: 
                   15492: =head2 General File Helper Routines
                   15493: 
                   15494: =over 4
1.191     harris41 15495: 
                   15496: =item *
                   15497: 
1.481     raeburn  15498: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15499: (a) files in /uploaded
                   15500:   (i) If a local copy of the file exists - 
                   15501:       compares modification date of local copy with last-modified date for 
                   15502:       definitive version stored on home server for course. If local copy is 
                   15503:       stale, requests a new version from the home server and stores it. 
                   15504:       If the original has been removed from the home server, then local copy 
                   15505:       is unlinked.
                   15506:   (ii) If local copy does not exist -
                   15507:       requests the file from the home server and stores it. 
                   15508:   
                   15509:   If $caller is 'uploadrep':  
                   15510:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15511:     for request for files originally uploaded via DOCS. 
                   15512:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15513:   
                   15514:   Otherwise:
                   15515:      This indicates a call from the content generation phase of the request.
                   15516:      -  returns the entire contents of the file or -1.
                   15517:      
                   15518: (b) files in /res
                   15519:    - returns the entire contents of a file or -1; 
                   15520:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15521: 
1.712     albertel 15522: 
                   15523: =item *
                   15524: 
                   15525: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15526:                   reference
                   15527: 
                   15528: returns either a stat() list of data about the file or an empty list
                   15529: if the file doesn't exist or couldn't find out about it (connection
                   15530: problems or user unknown)
                   15531: 
1.191     harris41 15532: =item *
                   15533: 
1.243     albertel 15534: filelocation($dir,$file) : returns file system location of a file
                   15535: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15536: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15537: and a file of ../bob will become /a/bob)
1.191     harris41 15538: 
                   15539: =item *
                   15540: 
                   15541: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15542: filelocation except for hrefs
                   15543: 
                   15544: =item *
                   15545: 
1.1172.2.49  raeburn  15546: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15547: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15548: 
1.243     albertel 15549: =back
                   15550: 
1.608     albertel 15551: =head2 Usererfile file routines (/uploaded*)
                   15552: 
                   15553: =over 4
                   15554: 
                   15555: =item *
                   15556: 
                   15557: userfileupload(): main rotine for putting a file in a user or course's
                   15558:                   filespace, arguments are,
                   15559: 
1.620     albertel 15560:  formname - required - this is the name of the element in $env where the
1.608     albertel 15561:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15562:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15563:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15564:  context - if coursedoc, store the file in the course of the active role
                   15565:              of the current user; 
                   15566:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15567:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15568:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15569:          if undefined, it will be placed in "unknown"
                   15570: 
                   15571:  (This routine calls clean_filename() to remove any dangerous
                   15572:  characters from the filename, and then calls finuserfileupload() to
                   15573:  complete the transaction)
                   15574: 
                   15575:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15576:  and /adm/notfound.html if unsuccessful
                   15577: 
                   15578: =item *
                   15579: 
                   15580: clean_filename(): routine for cleaing a filename up for storage in
                   15581:                  userfile space, argument is:
                   15582: 
                   15583:  filename - proposed filename
                   15584: 
                   15585: returns: the new clean filename
                   15586: 
                   15587: =item *
                   15588: 
1.1090    raeburn  15589: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15590: userspace, probably shouldn't be called directly
                   15591: 
                   15592:   docuname: username or courseid of destination for the file
                   15593:   docudom: domain of user/course of destination for the file
                   15594:   formname: same as for userfileupload()
1.1090    raeburn  15595:   fname: filename (including subdirectories) for the file
                   15596:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15597:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15598:   allfiles: reference to hash used to store objects found by parser
                   15599:   codebase: reference to hash used for codebases of java objects found by parser
                   15600:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15601:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15602:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15603:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15604:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15605:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15606:   mimetype: reference to scalar to accommodate mime type determined
                   15607:             from File::MMagic if $parser = parse.
1.608     albertel 15608: 
                   15609:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15610:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15611:  was 'overwrite').
                   15612:  
1.608     albertel 15613: 
                   15614: =item *
                   15615: 
                   15616: renameuserfile(): renames an existing userfile to a new name
                   15617: 
                   15618:   Args:
                   15619:    docuname: username or courseid of destination for the file
                   15620:    docudom: domain of user/course of destination for the file
                   15621:    old: current file name (including any subdirs under userfiles)
                   15622:    new: desired file name (including any subdirs under userfiles)
                   15623: 
                   15624: =item *
                   15625: 
                   15626: mkdiruserfile(): creates a directory is a userfiles dir
                   15627: 
                   15628:   Args:
                   15629:    docuname: username or courseid of destination for the file
                   15630:    docudom: domain of user/course of destination for the file
                   15631:    dir: dir to create (including any subdirs under userfiles)
                   15632: 
                   15633: =item *
                   15634: 
                   15635: removeuserfile(): removes a file that exists in userfiles
                   15636: 
                   15637:   Args:
                   15638:    docuname: username or courseid of destination for the file
                   15639:    docudom: domain of user/course of destination for the file
                   15640:    fname: filname to delete (including any subdirs under userfiles)
                   15641: 
                   15642: =item *
                   15643: 
                   15644: removeuploadedurl(): convience function for removeuserfile()
                   15645: 
                   15646:   Args:
                   15647:    url:  a full /uploaded/... url to delete
                   15648: 
1.747     albertel 15649: =item * 
                   15650: 
                   15651: get_portfile_permissions():
                   15652:   Args:
                   15653:     domain: domain of user or course contain the portfolio files
                   15654:     user: name of user or num of course contain the portfolio files
                   15655:   Returns:
                   15656:     hashref of a dump of the proper file_permissions.db
                   15657:    
                   15658: 
                   15659: =item * 
                   15660: 
                   15661: get_access_controls():
                   15662: 
                   15663: Args:
                   15664:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15665:   group: (optional) the group you want the files associated with
                   15666:   file: (optional) the file you want access info on
                   15667: 
                   15668: Returns:
1.749     raeburn  15669:     a hash (keys are file names) of hashes containing
                   15670:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15671:         values are XML containing access control settings (see below) 
1.747     albertel 15672: 
                   15673: Internal notes:
                   15674: 
1.749     raeburn  15675:  access controls are stored in file_permissions.db as key=value pairs.
                   15676:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15677:         where scope -> public,guest,course,group,domains or users.
                   15678:               end -> UNIX time for end of access (0 -> no end date)
                   15679:               start -> UNIX time for start of access
                   15680: 
                   15681:     value -> XML description of access control
                   15682:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15683:             <start></start>
                   15684:             <end></end>
                   15685: 
                   15686:             <password></password>  for scope type = guest
                   15687: 
                   15688:             <domain></domain>     for scope type = course or group
                   15689:             <number></number>
                   15690:             <roles id="">
                   15691:              <role></role>
                   15692:              <access></access>
                   15693:              <section></section>
                   15694:              <group></group>
                   15695:             </roles>
                   15696: 
                   15697:             <dom></dom>         for scope type = domains
                   15698: 
                   15699:             <users>             for scope type = users
                   15700:              <user>
                   15701:               <uname></uname>
                   15702:               <udom></udom>
                   15703:              </user>
                   15704:             </users>
                   15705:            </scope> 
                   15706:               
                   15707:  Access data is also aggregated for each file in an additional key=value pair:
                   15708:  key -> path to file/file_name\0accesscontrol 
                   15709:  value -> reference to hash
                   15710:           hash contains key = value pairs
                   15711:           where key = uniqueID:scope_end_start
                   15712:                 value = UNIX time record was last updated
                   15713: 
                   15714:           Used to improve speed of look-ups of access controls for each file.  
                   15715:  
                   15716:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15717: 
1.1172.2.13  raeburn  15718: =item *
                   15719: 
1.749     raeburn  15720: modify_access_controls():
                   15721: 
                   15722: Modifies access controls for a portfolio file
                   15723: Args
                   15724: 1. file name
                   15725: 2. reference to hash of required changes,
                   15726: 3. domain
                   15727: 4. username
                   15728:   where domain,username are the domain of the portfolio owner 
                   15729:   (either a user or a course) 
                   15730: 
                   15731: Returns:
                   15732: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15733: 2. result of deletions ('ok' or 'error', with error message).
                   15734: 3. reference to hash of any new or updated access controls.
                   15735: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15736:    key = integer (inbound ID)
1.1172.2.13  raeburn  15737:    value = uniqueID
                   15738: 
                   15739: =item *
                   15740: 
                   15741: get_timebased_id():
                   15742: 
                   15743: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15744: course via the Course Editor (e.g., folders, composite pages,
                   15745: group bulletin boards).
                   15746: 
                   15747: Args: (first three required; six others optional)
                   15748: 
                   15749: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15750:    docssequence, or name of group
                   15751: 
                   15752: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15753:    e.g., num, boardids
                   15754: 
                   15755: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15756:    file will be named nohist_namespace.db
                   15757: 
                   15758: 4. cdom: domain of course; default is current course domain from %env
                   15759: 
                   15760: 5. cnum: course number; default is current course number from %env
                   15761: 
                   15762: 6. idtype: set to concat if an additional digit is to be appended to the
                   15763:    unix timestamp to form the suffix, if the plain timestamp is already
                   15764:    in use.  Default is to not do this, but simply increment the unix
                   15765:    timestamp by 1 until a unique key is obtained.
                   15766: 
                   15767: 7. who: holder of locking key; defaults to user:domain for user.
                   15768: 
                   15769: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15770:    retrying); default is 3.
                   15771: 
                   15772: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15773: 
                   15774: Returns:
                   15775: 
                   15776: 1. suffix obtained (numeric)
                   15777: 
                   15778: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15779: 
                   15780: 3. error: contains (localized) error message if an error occurred.
                   15781: 
1.747     albertel 15782: 
1.608     albertel 15783: =back
                   15784: 
1.243     albertel 15785: =head2 HTTP Helper Routines
                   15786: 
                   15787: =over 4
                   15788: 
1.191     harris41 15789: =item *
                   15790: 
                   15791: escape() : unpack non-word characters into CGI-compatible hex codes
                   15792: 
                   15793: =item *
                   15794: 
                   15795: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15796: 
1.243     albertel 15797: =back
                   15798: 
                   15799: =head1 PRIVATE SUBROUTINES
                   15800: 
                   15801: =head2 Underlying communication routines (Shouldn't call)
                   15802: 
                   15803: =over 4
                   15804: 
                   15805: =item *
                   15806: 
                   15807: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15808: 
                   15809: =item *
                   15810: 
                   15811: reply() : uses subreply to send a message to remote machine, logs all failures
                   15812: 
                   15813: =item *
                   15814: 
                   15815: critical() : passes a critical message to another server; if cannot
                   15816: get through then place message in connection buffer directory and
                   15817: returns con_delayed, if incapable of saving message, returns
                   15818: con_failed
                   15819: 
                   15820: =item *
                   15821: 
                   15822: reconlonc() : tries to reconnect lonc client processes.
                   15823: 
                   15824: =back
                   15825: 
                   15826: =head2 Resource Access Logging
                   15827: 
                   15828: =over 4
                   15829: 
                   15830: =item *
                   15831: 
                   15832: flushcourselogs() : flush (save) buffer logs and access logs
                   15833: 
                   15834: =item *
                   15835: 
                   15836: courselog($what) : save message for course in hash
                   15837: 
                   15838: =item *
                   15839: 
                   15840: courseacclog($what) : save message for course using &courselog().  Perform
                   15841: special processing for specific resource types (problems, exams, quizzes, etc).
                   15842: 
1.191     harris41 15843: =item *
                   15844: 
                   15845: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15846: as a PerlChildExitHandler
1.243     albertel 15847: 
                   15848: =back
                   15849: 
                   15850: =head2 Other
                   15851: 
                   15852: =over 4
                   15853: 
                   15854: =item *
                   15855: 
                   15856: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15857: 
                   15858: =back
                   15859: 
                   15860: =cut
1.877     foxr     15861: 

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