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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.124! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.123 2020/05/04 15:07:10 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.120  raeburn   266:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   269:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.120  raeburn   960:                 my $protocol = 'http';
                    961:                 if ($protocol{$spare_server} eq 'https') {
                    962:                     $protocol = $protocol{$spare_server};
                    963:                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
                   1085: sub delbalcookie {
                   1086:     my ($cookie,$balancer) =@_;
                   1087:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:         my ($udom,$uname) = ($1,$2);
                   1089:         my $uprimary_id = &domain($udom,'primary');
                   1090:         my $uintdom = &internet_dom($uprimary_id);
                   1091:         my $intdom = &internet_dom($balancer);
                   1092:         my $serverhomedom = &host_domain($balancer);
                   1093:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:             return &reply("delbalcookie:$cookie",$balancer);
                   1095:         }
                   1096:     }
                   1097: }
                   1098: 
1.914     albertel 1099: # -------------------------------- ask if server already has a session for user
                   1100: sub has_user_session {
                   1101:     my ($lonid,$udom,$uname) = @_;
                   1102:     my $result = &reply(join(':','userhassession',
                   1103: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1104:     return 1 if ($result eq 'ok');
                   1105: 
                   1106:     return 0;
                   1107: }
                   1108: 
1.1076    raeburn  1109: # --------- determine least loaded server in a user's domain which allows login
                   1110: 
                   1111: sub choose_server {
1.1172.2.47  raeburn  1112:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1113:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1114:     my %servers = &get_servers($udom);
1.1076    raeburn  1115:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1116:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1117:     if ($skiploadbal) {
                   1118:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1119:         unless (defined($cached)) {
                   1120:             my $cachetime = 60*60*24;
                   1121:             my %domconfig =
                   1122:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1123:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1124:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1125:                                            $cachetime);
                   1126:             }
                   1127:         }
                   1128:     }
1.1076    raeburn  1129:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1130:         my $loginvia;
1.1172.2.47  raeburn  1131:         if ($skiploadbal) {
                   1132:             if (ref($balancers) eq 'HASH') {
                   1133:                 next if (exists($balancers->{$lonhost}));
                   1134:             }
                   1135:         }
1.1115    raeburn  1136:         if ($checkloginvia) {
                   1137:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1138:             if ($loginvia) {
                   1139:                 my ($server,$path) = split(/:/,$loginvia);
                   1140:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1141:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1142:                 if ($login_host eq $server) {
                   1143:                     $portal_path = $path;
1.1151    raeburn  1144:                     $isredirect = 1;
1.1116    raeburn  1145:                 }
                   1146:             } else {
                   1147:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1148:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1149:                 if ($login_host eq $lonhost) {
                   1150:                     $portal_path = '';
1.1151    raeburn  1151:                     $isredirect = ''; 
1.1116    raeburn  1152:                 }
                   1153:             }
                   1154:         } else {
1.1076    raeburn  1155:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1157:         }
                   1158:     }
                   1159:     if ($login_host ne '') {
1.1116    raeburn  1160:         $hostname = &hostname($login_host);
1.1076    raeburn  1161:     }
1.1172.2.88  raeburn  1162:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1163: }
                   1164: 
1.1172.2.123  raeburn  1165: sub get_course_sessions {
                   1166:     my ($cnum,$cdom,$lastactivity) = @_;
                   1167:     my %servers = &internet_dom_servers($cdom);
                   1168:     my %returnhash;
                   1169:     foreach my $server (sort(keys(%servers))) {
                   1170:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1171:         my @pairs=split(/\&/,$rep);
                   1172:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1173:             foreach my $item (@pairs) {
                   1174:                 my ($key,$value)=split(/=/,$item,2);
                   1175:                 $key = &unescape($key);
                   1176:                 next if ($key =~ /^error: 2 /);
                   1177:                 if (exists($returnhash{$key})) {
                   1178:                     next if ($value < $returnhash{$key});
                   1179:                 }
                   1180:                 $returnhash{$key}=$value;
                   1181:             }
                   1182:         }
                   1183:     }
                   1184:     return %returnhash;
                   1185: }
                   1186: 
1.202     matthew  1187: # --------------------------------------------- Try to change a user's password
                   1188: 
                   1189: sub changepass {
1.799     raeburn  1190:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1191:     $currentpass = &escape($currentpass);
                   1192:     $newpass     = &escape($newpass);
1.1030    raeburn  1193:     my $lonhost = $perlvar{'lonHostID'};
                   1194:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1195: 		       $server);
                   1196:     if (! $answer) {
                   1197: 	&logthis("No reply on password change request to $server ".
                   1198: 		 "by $uname in domain $udom.");
                   1199:     } elsif ($answer =~ "^ok") {
                   1200:         &logthis("$uname in $udom successfully changed their password ".
                   1201: 		 "on $server.");
                   1202:     } elsif ($answer =~ "^pwchange_failure") {
                   1203: 	&logthis("$uname in $udom was unable to change their password ".
                   1204: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1205: 		 "or pwchange");
                   1206:     } elsif ($answer =~ "^non_authorized") {
                   1207:         &logthis("$uname in $udom did not get their password correct when ".
                   1208: 		 "attempting to change it on $server.");
                   1209:     } elsif ($answer =~ "^auth_mode_error") {
                   1210:         &logthis("$uname in $udom attempted to change their password despite ".
                   1211: 		 "not being locally or internally authenticated on $server.");
                   1212:     } elsif ($answer =~ "^unknown_user") {
                   1213:         &logthis("$uname in $udom attempted to change their password ".
                   1214: 		 "on $server but were unable to because $server is not ".
                   1215: 		 "their home server.");
                   1216:     } elsif ($answer =~ "^refused") {
                   1217: 	&logthis("$server refused to change $uname in $udom password because ".
                   1218: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1219:     } elsif ($answer =~ "invalid_client") {
                   1220:         &logthis("$server refused to change $uname in $udom password because ".
                   1221:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1222:     } elsif ($answer =~ "^prioruse") {
                   1223:        &logthis("$server refused to change $uname in $udom password because ".
                   1224:                 "the password had been used before");
1.202     matthew  1225:     }
                   1226:     return $answer;
1.1       albertel 1227: }
                   1228: 
1.169     harris41 1229: # ----------------------- Try to determine user's current authentication scheme
                   1230: 
                   1231: sub queryauthenticate {
                   1232:     my ($uname,$udom)=@_;
1.456     albertel 1233:     my $uhome=&homeserver($uname,$udom);
                   1234:     if (!$uhome) {
                   1235: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1236: 	return 'no_host';
                   1237:     }
                   1238:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1239:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1240: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1241:     }
1.456     albertel 1242:     return $answer;
1.169     harris41 1243: }
                   1244: 
1.1       albertel 1245: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1246: 
1.1       albertel 1247: sub authenticate {
1.1073    raeburn  1248:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1249:     $upass=&escape($upass);
                   1250:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1251:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1252:     my $newhome;
1.836     www      1253:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1254: # Maybe the machine was offline and only re-appeared again recently?
                   1255:         &reconlonc();
                   1256: # One more
1.952     raeburn  1257: 	$uhome=&homeserver($uname,$udom,1);
                   1258:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1259:             if (defined(&domain($udom,'primary'))) {
                   1260:                 $newhome=&domain($udom,'primary');
                   1261:             }
                   1262:             if ($newhome ne '') {
                   1263:                 $uhome = $newhome;
                   1264:             }
                   1265:         }
1.836     www      1266: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1267: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1268: 	    return 'no_host';
                   1269:         }
1.1       albertel 1270:     }
1.1073    raeburn  1271:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1272:     if ($answer eq 'authorized') {
1.952     raeburn  1273:         if ($newhome) {
                   1274:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1275:             return 'no_account_on_host'; 
                   1276:         } else {
                   1277:             &logthis("User $uname at $udom authorized by $uhome");
                   1278:             return $uhome;
                   1279:         }
1.471     albertel 1280:     }
                   1281:     if ($answer eq 'non_authorized') {
                   1282: 	&logthis("User $uname at $udom rejected by $uhome");
                   1283: 	return 'no_host'; 
1.9       www      1284:     }
1.471     albertel 1285:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1286:     return 'no_host';
                   1287: }
                   1288: 
1.1073    raeburn  1289: sub can_host_session {
1.1074    raeburn  1290:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1291:     my $canhost = 1;
1.1074    raeburn  1292:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1293:     if (ref($remotesessions) eq 'HASH') {
                   1294:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1295:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1296:                 $canhost = 0;
                   1297:             } else {
                   1298:                 $canhost = 1;
                   1299:             }
                   1300:         }
                   1301:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1302:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1303:                 $canhost = 1;
                   1304:             } else {
                   1305:                 $canhost = 0;
                   1306:             }
                   1307:         }
                   1308:         if ($canhost) {
                   1309:             if ($remotesessions->{'version'} ne '') {
                   1310:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1311:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1312:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1313:                         my $major = $1;
                   1314:                         my $minor = $2;
                   1315:                         if (($major < $reqmajor ) ||
                   1316:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1317:                             $canhost = 0;
                   1318:                         }
                   1319:                     } else {
                   1320:                         $canhost = 0;
                   1321:                     }
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     if ($canhost) {
                   1327:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1328:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1329:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1330:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1331:                 if (($uint_dom ne '') && 
                   1332:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1333:                     $canhost = 0;
                   1334:                 } else {
                   1335:                     $canhost = 1;
                   1336:                 }
                   1337:             }
                   1338:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1339:                 if (($uint_dom ne '') && 
                   1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1341:                     $canhost = 1;
                   1342:                 } else {
                   1343:                     $canhost = 0;
                   1344:                 }
                   1345:             }
                   1346:         }
                   1347:     }
                   1348:     return $canhost;
                   1349: }
                   1350: 
1.1083    raeburn  1351: sub spare_can_host {
                   1352:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1353:     my $canhost=1;
1.1172.2.62  raeburn  1354:     my $try_server_hostname = &hostname($try_server);
                   1355:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1356:     my $serverhomedom = &host_domain($serverhomeID);
                   1357:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1358:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1359:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1360:             $canhost = 0;
                   1361:         }
                   1362:     }
                   1363:     if (($canhost) && ($uint_dom)) {
                   1364:         my @intdoms;
                   1365:         my $internet_names = &get_internet_names($try_server);
                   1366:         if (ref($internet_names) eq 'ARRAY') {
                   1367:             @intdoms = @{$internet_names};
                   1368:         }
                   1369:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1370:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1371:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1372:                                          $remotesessions,
                   1373:                                          $defdomdefaults{'hostedsessions'});
                   1374:         }
1.1083    raeburn  1375:     }
                   1376:     return $canhost;
                   1377: }
                   1378: 
1.1123    raeburn  1379: sub this_host_spares {
                   1380:     my ($dom) = @_;
1.1126    raeburn  1381:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1382:     my @hosts = &current_machine_ids();
                   1383:     foreach my $lonhost (@hosts) {
                   1384:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1385:             $dom_in_use = $dom;
                   1386:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1387:             last;
                   1388:         }
                   1389:     }
1.1126    raeburn  1390:     if ($dom_in_use ne '') {
                   1391:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1392:     }
                   1393:     if (ref($result) ne 'HASH') {
                   1394:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1395:         $dom_in_use = &host_domain($lonhost_in_use);
                   1396:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1397:         if (ref($result) ne 'HASH') {
                   1398:             $result = \%spareid;
                   1399:         }
                   1400:     }
                   1401:     return $result;
                   1402: }
                   1403: 
                   1404: sub spares_for_offload  {
                   1405:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1406:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1407:     if (defined($cached)) {
                   1408:         return $result;
                   1409:     } else {
1.1126    raeburn  1410:         my $cachetime = 60*60*24;
                   1411:         my %domconfig =
                   1412:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1413:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1414:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1415:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1416:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1417:                 }
                   1418:             }
                   1419:         }
                   1420:     }
1.1126    raeburn  1421:     return;
1.1123    raeburn  1422: }
                   1423: 
1.1129    raeburn  1424: sub get_lonbalancer_config {
                   1425:     my ($servers) = @_;
                   1426:     my ($currbalancer,$currtargets);
                   1427:     if (ref($servers) eq 'HASH') {
                   1428:         foreach my $server (keys(%{$servers})) {
                   1429:             my %what = (
                   1430:                          spareid => 1,
                   1431:                          perlvar => 1,
                   1432:                        );
                   1433:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1434:             if ($result eq 'ok') {
                   1435:                 if (ref($returnhash) eq 'HASH') {
                   1436:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1437:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1438:                             $currbalancer = $server;
                   1439:                             $currtargets = {};
                   1440:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1441:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1442:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1443:                                 }
                   1444:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1445:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1446:                                 }
                   1447:                             }
                   1448:                             last;
                   1449:                         }
                   1450:                     }
                   1451:                 }
                   1452:             }
                   1453:         }
                   1454:     }
                   1455:     return ($currbalancer,$currtargets);
                   1456: }
                   1457: 
                   1458: sub check_loadbalancing {
1.1172.2.88  raeburn  1459:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1460:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1461:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1462:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1463:     my @hosts = &current_machine_ids();
1.1129    raeburn  1464:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1465:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1466:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1467:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1468:     my $domneedscache; 
1.1129    raeburn  1469:     my $cachetime = 60*60*24;
                   1470: 
                   1471:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1472:         $dom_in_use = $udom;
                   1473:         $homeintdom = 1;
                   1474:     } else {
                   1475:         $dom_in_use = $serverhomedom;
                   1476:     }
                   1477:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1478:     unless (defined($cached)) {
                   1479:         my %domconfig =
                   1480:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1481:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1482:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1483:         } else {
                   1484:             $domneedscache = $dom_in_use;
1.1129    raeburn  1485:         }
                   1486:     }
                   1487:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1488:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1489:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1490:         if ($is_balancer) {
                   1491:             if (ref($currrules) eq 'HASH') {
                   1492:                 if ($homeintdom) {
                   1493:                     if ($uname ne '') {
                   1494:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1495:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1496:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1497:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1498:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1499:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1500:                             }
                   1501:                         }
                   1502:                         if ($rule_in_effect eq '') {
                   1503:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1504:                             if ($userenv{'inststatus'} ne '') {
                   1505:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1506:                                 my ($othertitle,$usertypes,$types) =
                   1507:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1508:                                 if (ref($types) eq 'ARRAY') {
                   1509:                                     foreach my $type (@{$types}) {
                   1510:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1511:                                             if (exists($currrules->{$type})) {
                   1512:                                                 $rule_in_effect = $currrules->{$type};
                   1513:                                             }
                   1514:                                         }
                   1515:                                     }
                   1516:                                 }
                   1517:                             } else {
                   1518:                                 if (exists($currrules->{'default'})) {
                   1519:                                     $rule_in_effect = $currrules->{'default'};
                   1520:                                 }
                   1521:                             }
                   1522:                         }
                   1523:                     } else {
                   1524:                         if (exists($currrules->{'default'})) {
                   1525:                             $rule_in_effect = $currrules->{'default'};
                   1526:                         }
                   1527:                     }
                   1528:                 } else {
                   1529:                     if ($currrules->{'_LC_external'} ne '') {
                   1530:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1531:                     }
                   1532:                 }
                   1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1534:                                                        $uname,$udom);
                   1535:             }
                   1536:         }
                   1537:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1538:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1539:         unless (defined($cached)) {
                   1540:             my %domconfig =
                   1541:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1542:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1543:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1544:             } else {
                   1545:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1546:             }
                   1547:         }
                   1548:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1549:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1550:                 &check_balancer_result($result,@hosts);
                   1551:             if ($is_balancer) {
1.1129    raeburn  1552:                 if (ref($currrules) eq 'HASH') {
                   1553:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1554:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1555:                     }
                   1556:                 }
                   1557:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1558:                                                        $uname,$udom);
                   1559:             }
                   1560:         } else {
                   1561:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1562:                 $is_balancer = 1;
                   1563:                 $offloadto = &this_host_spares($dom_in_use);
                   1564:             }
1.1172.2.75  raeburn  1565:             unless (defined($cached)) {
                   1566:                 $domneedscache = $serverhomedom;
                   1567:             }
1.1129    raeburn  1568:         }
                   1569:     } else {
                   1570:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1571:             $is_balancer = 1;
                   1572:             $offloadto = &this_host_spares($dom_in_use);
                   1573:         }
1.1172.2.75  raeburn  1574:         unless (defined($cached)) {
                   1575:             $domneedscache = $serverhomedom;
                   1576:         }
                   1577:     }
                   1578:     if ($domneedscache) {
                   1579:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1580:     }
1.1172.2.5  raeburn  1581:     if ($is_balancer) {
                   1582:         my $lowest_load = 30000;
                   1583:         if (ref($offloadto) eq 'HASH') {
                   1584:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1585:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1586:                     ($otherserver,$lowest_load) =
                   1587:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1588:                 }
1.1129    raeburn  1589:             }
1.1172.2.5  raeburn  1590:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1591: 
1.1172.2.5  raeburn  1592:             if (!$found_server) {
                   1593:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1594:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1595:                         ($otherserver,$lowest_load) =
                   1596:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1597:                     }
                   1598:                 }
                   1599:             }
                   1600:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1601:             if (@{$offloadto} == 1) {
                   1602:                 $otherserver = $offloadto->[0];
                   1603:             } elsif (@{$offloadto} > 1) {
                   1604:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1605:                     ($otherserver,$lowest_load) =
                   1606:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1607:                 }
                   1608:             }
                   1609:         }
1.1172.2.88  raeburn  1610:         unless ($caller eq 'login') {
                   1611:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1612:                 $is_balancer = 0;
                   1613:                 if ($uname ne '' && $udom ne '') {
                   1614:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1615:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1616:                                  'user.loadbalcheck.time' => time});
                   1617:                     }
1.1172.2.5  raeburn  1618:                 }
1.1129    raeburn  1619:             }
                   1620:         }
1.1172.2.107  raeburn  1621:         unless ($homeintdom) {
                   1622:             undef($setcookie);
                   1623:         }
1.1129    raeburn  1624:     }
1.1172.2.107  raeburn  1625:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1626: }
                   1627: 
1.1172.2.12  raeburn  1628: sub check_balancer_result {
                   1629:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1630:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1631:     if (ref($result) eq 'HASH') {
                   1632:         if ($result->{'lonhost'} ne '') {
                   1633:             my $currbalancer = $result->{'lonhost'};
                   1634:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1635:                 $is_balancer = 1;
                   1636:                 $currtargets = $result->{'targets'};
                   1637:                 $currrules = $result->{'rules'};
                   1638:             }
                   1639:         } else {
                   1640:             foreach my $key (keys(%{$result})) {
                   1641:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1642:                     (ref($result->{$key}) eq 'HASH')) {
                   1643:                     $is_balancer = 1;
                   1644:                     $currrules = $result->{$key}{'rules'};
                   1645:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1646:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1647:                     last;
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
1.1172.2.107  raeburn  1652:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1653: }
                   1654: 
1.1129    raeburn  1655: sub get_loadbalancer_targets {
                   1656:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1657:     my $offloadto;
1.1172.2.4  raeburn  1658:     if ($rule_in_effect eq 'none') {
                   1659:         return [$perlvar{'lonHostID'}];
                   1660:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1661:         $offloadto = $currtargets;
                   1662:     } else {
                   1663:         if ($rule_in_effect eq 'homeserver') {
                   1664:             my $homeserver = &homeserver($uname,$udom);
                   1665:             if ($homeserver ne 'no_host') {
                   1666:                 $offloadto = [$homeserver];
                   1667:             }
                   1668:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1669:             my %domconfig =
                   1670:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1671:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1672:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1673:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1674:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1675:                     }
                   1676:                 }
                   1677:             } else {
1.1172.2.7  raeburn  1678:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1679:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1680:                 if (&hostname($remotebalancer) ne '') {
                   1681:                     $offloadto = [$remotebalancer];
                   1682:                 }
                   1683:             }
                   1684:         } elsif (&hostname($rule_in_effect) ne '') {
                   1685:             $offloadto = [$rule_in_effect];
                   1686:         }
                   1687:     }
                   1688:     return $offloadto;
                   1689: }
                   1690: 
1.1127    raeburn  1691: sub internet_dom_servers {
                   1692:     my ($dom) = @_;
                   1693:     my (%uniqservers,%servers);
                   1694:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1695:     my @machinedoms = &machine_domains($primaryserver);
                   1696:     foreach my $mdom (@machinedoms) {
                   1697:         my %currservers = %servers;
                   1698:         my %server = &get_servers($mdom);
                   1699:         %servers = (%currservers,%server);
                   1700:     }
                   1701:     my %by_hostname;
                   1702:     foreach my $id (keys(%servers)) {
                   1703:         push(@{$by_hostname{$servers{$id}}},$id);
                   1704:     }
                   1705:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1706:         if (@{$by_hostname{$hostname}} > 1) {
                   1707:             my $match = 0;
                   1708:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1709:                 if (&host_domain($id) eq $dom) {
                   1710:                     $uniqservers{$id} = $hostname;
                   1711:                     $match = 1;
                   1712:                 }
                   1713:             }
                   1714:             unless ($match) {
                   1715:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1716:             }
                   1717:         } else {
                   1718:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1719:         }
                   1720:     }
                   1721:     return %uniqservers;
                   1722: }
                   1723: 
1.1       albertel 1724: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1725: 
1.599     albertel 1726: my %homecache;
1.1       albertel 1727: sub homeserver {
1.230     stredwic 1728:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1729:     my $index="$uname:$udom";
1.426     albertel 1730: 
1.599     albertel 1731:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1732: 
                   1733:     my %servers = &get_servers($udom,'library');
                   1734:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1735:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1736: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1737: 
                   1738: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1739: 	if ($answer eq 'found') {
                   1740: 	    delete($badServerCache{$tryserver}); 
                   1741: 	    return $homecache{$index}=$tryserver;
                   1742: 	} elsif ($answer eq 'no_host') {
                   1743: 	    $badServerCache{$tryserver}=1;
                   1744: 	}
1.1       albertel 1745:     }    
                   1746:     return 'no_host';
1.70      www      1747: }
                   1748: 
                   1749: # ------------------------------------- Find the usernames behind a list of IDs
                   1750: 
                   1751: sub idget {
                   1752:     my ($udom,@ids)=@_;
                   1753:     my %returnhash=();
                   1754:     
1.841     albertel 1755:     my %servers = &get_servers($udom,'library');
                   1756:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1757: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1758: 	$idlist=~tr/A-Z/a-z/; 
                   1759: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1760: 	my @answer=();
                   1761: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1762: 	    @answer=split(/\&/,$reply);
                   1763: 	}                    ;
                   1764: 	my $i;
                   1765: 	for ($i=0;$i<=$#ids;$i++) {
                   1766: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1767: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1768: 	    } 
                   1769: 	}
                   1770:     } 
1.70      www      1771:     return %returnhash;
                   1772: }
                   1773: 
                   1774: # ------------------------------------- Find the IDs behind a list of usernames
                   1775: 
                   1776: sub idrget {
                   1777:     my ($udom,@unames)=@_;
                   1778:     my %returnhash=();
1.800     albertel 1779:     foreach my $uname (@unames) {
                   1780:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1781:     }
1.70      www      1782:     return %returnhash;
                   1783: }
                   1784: 
                   1785: # ------------------------------- Store away a list of names and associated IDs
                   1786: 
                   1787: sub idput {
                   1788:     my ($udom,%ids)=@_;
                   1789:     my %servers=();
1.800     albertel 1790:     foreach my $uname (keys(%ids)) {
                   1791: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1792:         my $uhom=&homeserver($uname,$udom);
1.70      www      1793:         if ($uhom ne 'no_host') {
1.800     albertel 1794:             my $id=&escape($ids{$uname});
1.70      www      1795:             $id=~tr/A-Z/a-z/;
1.800     albertel 1796:             my $esc_unam=&escape($uname);
1.70      www      1797: 	    if ($servers{$uhom}) {
1.800     albertel 1798: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1799:             } else {
1.800     albertel 1800:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1801:             }
                   1802:         }
1.191     harris41 1803:     }
1.800     albertel 1804:     foreach my $server (keys(%servers)) {
                   1805:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1806:     }
1.344     www      1807: }
                   1808: 
1.1172.2.30  raeburn  1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1810: 
                   1811: sub iddel {
                   1812:     my ($udom,$idshashref,$uhome)=@_;
                   1813:     my %result=();
                   1814:     unless (ref($idshashref) eq 'HASH') {
                   1815:         return %result;
                   1816:     }
                   1817:     my %servers=();
                   1818:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1819:         my $uhom;
                   1820:         if ($uhome) {
                   1821:             $uhom = $uhome;
                   1822:         } else {
                   1823:             $uhom=&homeserver($uname,$udom);
                   1824:         }
                   1825:         if ($uhom ne 'no_host') {
                   1826:             if ($servers{$uhom}) {
                   1827:                 $servers{$uhom}.='&'.&escape($id);
                   1828:             } else {
                   1829:                 $servers{$uhom}=&escape($id);
                   1830:             }
                   1831:         }
                   1832:     }
                   1833:     foreach my $server (keys(%servers)) {
                   1834:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1835:     }
                   1836:     return %result;
                   1837: }
                   1838: 
1.1023    raeburn  1839: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1840: sub dump_dom {
1.1165    droeschl 1841:     my ($namespace, $udom, $regexp) = @_;
                   1842: 
                   1843:     $udom ||= $env{'user.domain'};
                   1844: 
                   1845:     return () unless $udom;
                   1846: 
                   1847:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1848: }
                   1849: 
1.1023    raeburn  1850: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1851: 
                   1852: sub get_dom {
1.860     raeburn  1853:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1854:     return if ($udom eq 'public');
1.806     raeburn  1855:     my $items='';
                   1856:     foreach my $item (@$storearr) {
                   1857:         $items.=&escape($item).'&';
                   1858:     }
                   1859:     $items=~s/\&$//;
1.860     raeburn  1860:     if (!$udom) {
                   1861:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1862:         return if ($udom eq 'public');
1.860     raeburn  1863:         if (defined(&domain($udom,'primary'))) {
                   1864:             $uhome=&domain($udom,'primary');
                   1865:         } else {
1.874     albertel 1866:             undef($uhome);
1.860     raeburn  1867:         }
                   1868:     } else {
                   1869:         if (!$uhome) {
                   1870:             if (defined(&domain($udom,'primary'))) {
                   1871:                 $uhome=&domain($udom,'primary');
                   1872:             }
                   1873:         }
                   1874:     }
                   1875:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1876:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1877:         my %returnhash;
1.875     albertel 1878:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1879:             return %returnhash;
                   1880:         }
1.806     raeburn  1881:         my @pairs=split(/\&/,$rep);
                   1882:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1883:             return @pairs;
                   1884:         }
                   1885:         my $i=0;
                   1886:         foreach my $item (@$storearr) {
                   1887:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1888:             $i++;
                   1889:         }
                   1890:         return %returnhash;
                   1891:     } else {
1.880     banghart 1892:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1893:     }
                   1894: }
                   1895: 
                   1896: # -------------------------------------------- put items in domain db files 
                   1897: 
                   1898: sub put_dom {
1.860     raeburn  1899:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1900:     if (!$udom) {
                   1901:         $udom=$env{'user.domain'};
                   1902:         if (defined(&domain($udom,'primary'))) {
                   1903:             $uhome=&domain($udom,'primary');
                   1904:         } else {
1.874     albertel 1905:             undef($uhome);
1.860     raeburn  1906:         }
                   1907:     } else {
                   1908:         if (!$uhome) {
                   1909:             if (defined(&domain($udom,'primary'))) {
                   1910:                 $uhome=&domain($udom,'primary');
                   1911:             }
                   1912:         }
                   1913:     } 
                   1914:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1915:         my $items='';
                   1916:         foreach my $item (keys(%$storehash)) {
                   1917:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1918:         }
                   1919:         $items=~s/\&$//;
                   1920:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1921:     } else {
1.860     raeburn  1922:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1923:     }
                   1924: }
                   1925: 
1.1023    raeburn  1926: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1927: sub newput_dom {
1.1023    raeburn  1928:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1929:     my $result;
                   1930:     if (!$udom) {
                   1931:         $udom=$env{'user.domain'};
                   1932:     }
1.1023    raeburn  1933:     if ($udom) {
                   1934:         my $uname = &get_domainconfiguser($udom);
                   1935:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1936:     }
                   1937:     return $result;
                   1938: }
                   1939: 
1.1023    raeburn  1940: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1941: sub del_dom {
1.1023    raeburn  1942:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1943:     if (ref($storearr) eq 'ARRAY') {
                   1944:         if (!$udom) {
                   1945:             $udom=$env{'user.domain'};
                   1946:         }
1.1023    raeburn  1947:         if ($udom) {
                   1948:             my $uname = &get_domainconfiguser($udom); 
                   1949:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1950:         }
                   1951:     }
                   1952: }
                   1953: 
1.1023    raeburn  1954: # ----------------------------------construct domainconfig user for a domain 
                   1955: sub get_domainconfiguser {
                   1956:     my ($udom) = @_;
                   1957:     return $udom.'-domainconfig';
                   1958: }
                   1959: 
1.837     raeburn  1960: sub retrieve_inst_usertypes {
                   1961:     my ($udom) = @_;
                   1962:     my (%returnhash,@order);
1.989     raeburn  1963:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1964:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1965:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1966:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1967:     } else {
                   1968:         if (defined(&domain($udom,'primary'))) {
                   1969:             my $uhome=&domain($udom,'primary');
                   1970:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1971:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1972:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1973:                 return (\%returnhash,\@order);
                   1974:             }
                   1975:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1976:             my @pairs=split(/\&/,$hashitems);
                   1977:             foreach my $item (@pairs) {
                   1978:                 my ($key,$value)=split(/=/,$item,2);
                   1979:                 $key = &unescape($key);
                   1980:                 next if ($key =~ /^error: 2 /);
                   1981:                 $returnhash{$key}=&thaw_unescape($value);
                   1982:             }
                   1983:             my @esc_order = split(/\&/,$orderitems);
                   1984:             foreach my $item (@esc_order) {
                   1985:                 push(@order,&unescape($item));
                   1986:             }
                   1987:         } else {
1.1172.2.44  raeburn  1988:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1989:         }
1.1172.2.44  raeburn  1990:         return (\%returnhash,\@order);
1.837     raeburn  1991:     }
                   1992: }
                   1993: 
1.868     raeburn  1994: sub is_domainimage {
                   1995:     my ($url) = @_;
1.1172.2.74  raeburn  1996:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1997:         if (&domain($1) ne '') {
                   1998:             return '1';
                   1999:         }
                   2000:     }
                   2001:     return;
                   2002: }
                   2003: 
1.899     raeburn  2004: sub inst_directory_query {
                   2005:     my ($srch) = @_;
                   2006:     my $udom = $srch->{'srchdomain'};
                   2007:     my %results;
                   2008:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2009:     my $outcome;
1.899     raeburn  2010:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2011:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2012:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2013:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2014:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2015:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2016:                     (($major == 2) && ($minor < 11)) ||
                   2017:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2018:                     return;
                   2019:                 }
                   2020:             }
                   2021:         }
1.904     albertel 2022: 	my $queryid=&reply("querysend:instdirsearch:".
                   2023: 			   &escape($srch->{'srchby'}).':'.
                   2024: 			   &escape($srch->{'srchterm'}).':'.
                   2025: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2026: 	my $host=&hostname($homeserver);
                   2027: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2028: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2029: 	    return;
                   2030: 	}
                   2031: 	my $response = &get_query_reply($queryid);
                   2032: 	my $maxtries = 5;
                   2033: 	my $tries = 1;
                   2034: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2035: 	    $response = &get_query_reply($queryid);
                   2036: 	    $tries ++;
                   2037: 	}
                   2038: 
                   2039:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2040:             if ($response eq 'unavailable') {
                   2041:                 $outcome = $response;
                   2042:             } else {
                   2043:                 $outcome = 'ok';
                   2044:                 my @matches = split(/\n/,$response);
                   2045:                 foreach my $match (@matches) {
                   2046:                     my ($key,$value) = split(/=/,$match);
                   2047:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2048:                 }
1.899     raeburn  2049:             }
                   2050:         }
                   2051:     }
1.909     raeburn  2052:     return ($outcome,%results);
1.899     raeburn  2053: }
                   2054: 
                   2055: sub usersearch {
                   2056:     my ($srch) = @_;
                   2057:     my $dom = $srch->{'srchdomain'};
                   2058:     my %results;
                   2059:     my %libserv = &all_library();
                   2060:     my $query = 'usersearch';
                   2061:     foreach my $tryserver (keys(%libserv)) {
                   2062:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2063:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2064:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2065:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2066:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2067:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2068:                              (($major == 2) && ($minor < 11)) ||
                   2069:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2070:                 }
                   2071:             }
1.899     raeburn  2072:             my $host=&hostname($tryserver);
                   2073:             my $queryid=
1.911     raeburn  2074:                 &reply("querysend:".&escape($query).':'.
                   2075:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2076:                        &escape($srch->{'srchtype'}).':'.
                   2077:                        &escape($srch->{'srchterm'}),$tryserver);
                   2078:             if ($queryid !~/^\Q$host\E\_/) {
                   2079:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2080:                 next;
1.899     raeburn  2081:             }
                   2082:             my $reply = &get_query_reply($queryid);
                   2083:             my $maxtries = 1;
                   2084:             my $tries = 1;
                   2085:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2086:                 $reply = &get_query_reply($queryid);
                   2087:                 $tries ++;
                   2088:             }
                   2089:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2090:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2091:             } else {
1.911     raeburn  2092:                 my @matches;
                   2093:                 if ($reply =~ /\n/) {
                   2094:                     @matches = split(/\n/,$reply);
                   2095:                 } else {
                   2096:                     @matches = split(/\&/,$reply);
                   2097:                 }
1.899     raeburn  2098:                 foreach my $match (@matches) {
                   2099:                     my ($uname,$udom,%userhash);
1.911     raeburn  2100:                     foreach my $entry (split(/:/,$match)) {
                   2101:                         my ($key,$value) =
                   2102:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2103:                         $userhash{$key} = $value;
                   2104:                         if ($key eq 'username') {
                   2105:                             $uname = $value;
                   2106:                         } elsif ($key eq 'domain') {
                   2107:                             $udom = $value;
1.911     raeburn  2108:                         }
1.899     raeburn  2109:                     }
                   2110:                     $results{$uname.':'.$udom} = \%userhash;
                   2111:                 }
                   2112:             }
                   2113:         }
                   2114:     }
                   2115:     return %results;
                   2116: }
                   2117: 
1.912     raeburn  2118: sub get_instuser {
                   2119:     my ($udom,$uname,$id) = @_;
                   2120:     my $homeserver = &domain($udom,'primary');
                   2121:     my ($outcome,%results);
                   2122:     if ($homeserver ne '') {
                   2123:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2124:                            &escape($id).':'.&escape($udom),$homeserver);
                   2125:         my $host=&hostname($homeserver);
                   2126:         if ($queryid !~/^\Q$host\E\_/) {
                   2127:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2128:             return;
                   2129:         }
                   2130:         my $response = &get_query_reply($queryid);
                   2131:         my $maxtries = 5;
                   2132:         my $tries = 1;
                   2133:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2134:             $response = &get_query_reply($queryid);
                   2135:             $tries ++;
                   2136:         }
                   2137:         if (!&error($response) && $response ne 'refused') {
                   2138:             if ($response eq 'unavailable') {
                   2139:                 $outcome = $response;
                   2140:             } else {
                   2141:                 $outcome = 'ok';
                   2142:                 my @matches = split(/\n/,$response);
                   2143:                 foreach my $match (@matches) {
                   2144:                     my ($key,$value) = split(/=/,$match);
                   2145:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2146:                 }
                   2147:             }
                   2148:         }
                   2149:     }
                   2150:     my %userinfo;
                   2151:     if (ref($results{$uname}) eq 'HASH') {
                   2152:         %userinfo = %{$results{$uname}};
                   2153:     } 
                   2154:     return ($outcome,%userinfo);
                   2155: }
                   2156: 
1.1172.2.69  raeburn  2157: sub get_multiple_instusers {
                   2158:     my ($udom,$users,$caller) = @_;
                   2159:     my ($outcome,$results);
                   2160:     if (ref($users) eq 'HASH') {
                   2161:         my $count = keys(%{$users});
                   2162:         my $requested = &freeze_escape($users);
                   2163:         my $homeserver = &domain($udom,'primary');
                   2164:         if ($homeserver ne '') {
                   2165:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2166:             my $host=&hostname($homeserver);
                   2167:             if ($queryid !~/^\Q$host\E\_/) {
                   2168:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2169:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2170:                 return ($outcome,$results);
                   2171:             }
                   2172:             my $response = &get_query_reply($queryid);
                   2173:             my $maxtries = 5;
                   2174:             if ($count > 100) {
                   2175:                 $maxtries = 1+int($count/20);
                   2176:             }
                   2177:             my $tries = 1;
                   2178:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2179:                 $response = &get_query_reply($queryid);
                   2180:                 $tries ++;
                   2181:             }
                   2182:             if ($response eq '') {
                   2183:                 $results = {};
                   2184:                 foreach my $key (keys(%{$users})) {
                   2185:                     my ($uname,$id);
                   2186:                     if ($caller eq 'id') {
                   2187:                         $id = $key;
                   2188:                     } else {
                   2189:                         $uname = $key;
                   2190:                     }
                   2191:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2192:                     $outcome = $resp;
                   2193:                     if ($resp eq 'ok') {
                   2194:                         %{$results} = (%{$results}, %info);
                   2195:                     } else {
                   2196:                         last;
                   2197:                     }
                   2198:                 }
                   2199:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2200:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2201:                     $outcome = $response;
                   2202:                 } else {
                   2203:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2204:                     if ($outcome eq 'ok') {
                   2205:                         $results = &thaw_unescape($userdata);
                   2206:                     }
                   2207:                 }
                   2208:             }
                   2209:         }
                   2210:     }
                   2211:     return ($outcome,$results);
                   2212: }
                   2213: 
1.912     raeburn  2214: sub inst_rulecheck {
1.923     raeburn  2215:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2216:     my %returnhash;
                   2217:     if ($udom ne '') {
                   2218:         if (ref($rules) eq 'ARRAY') {
                   2219:             @{$rules} = map {&escape($_);} (@{$rules});
                   2220:             my $rulestr = join(':',@{$rules});
                   2221:             my $homeserver=&domain($udom,'primary');
                   2222:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2223:                 my $response;
                   2224:                 if ($item eq 'username') {                
                   2225:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2226:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2227:                                               $homeserver));
1.923     raeburn  2228:                 } elsif ($item eq 'id') {
                   2229:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2230:                                               ':'.&escape($id).':'.$rulestr,
                   2231:                                               $homeserver));
1.945     raeburn  2232:                 } elsif ($item eq 'selfcreate') {
                   2233:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2234:                                                &escape($udom).':'.&escape($uname).
                   2235:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2236:                 }
1.912     raeburn  2237:                 if ($response ne 'refused') {
                   2238:                     my @pairs=split(/\&/,$response);
                   2239:                     foreach my $item (@pairs) {
                   2240:                         my ($key,$value)=split(/=/,$item,2);
                   2241:                         $key = &unescape($key);
                   2242:                         next if ($key =~ /^error: 2 /);
                   2243:                         $returnhash{$key}=&thaw_unescape($value);
                   2244:                     }
                   2245:                 }
                   2246:             }
                   2247:         }
                   2248:     }
                   2249:     return %returnhash;
                   2250: }
                   2251: 
                   2252: sub inst_userrules {
1.923     raeburn  2253:     my ($udom,$check) = @_;
1.912     raeburn  2254:     my (%ruleshash,@ruleorder);
                   2255:     if ($udom ne '') {
                   2256:         my $homeserver=&domain($udom,'primary');
                   2257:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2258:             my $response;
                   2259:             if ($check eq 'id') {
                   2260:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2261:                                  $homeserver);
1.943     raeburn  2262:             } elsif ($check eq 'email') {
                   2263:                 $response=&reply('instemailrules:'.&escape($udom),
                   2264:                                  $homeserver);
1.923     raeburn  2265:             } else {
                   2266:                 $response=&reply('instuserrules:'.&escape($udom),
                   2267:                                  $homeserver);
                   2268:             }
1.912     raeburn  2269:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2270:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2271:                 ($response ne 'no_such_host')) {
                   2272:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2273:                 my @pairs=split(/\&/,$hashitems);
                   2274:                 foreach my $item (@pairs) {
                   2275:                     my ($key,$value)=split(/=/,$item,2);
                   2276:                     $key = &unescape($key);
                   2277:                     next if ($key =~ /^error: 2 /);
                   2278:                     $ruleshash{$key}=&thaw_unescape($value);
                   2279:                 }
                   2280:                 my @esc_order = split(/\&/,$orderitems);
                   2281:                 foreach my $item (@esc_order) {
                   2282:                     push(@ruleorder,&unescape($item));
                   2283:                 }
                   2284:             }
                   2285:         }
                   2286:     }
                   2287:     return (\%ruleshash,\@ruleorder);
                   2288: }
                   2289: 
1.976     raeburn  2290: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2291: 
                   2292: sub get_domain_defaults {
1.1172.2.35  raeburn  2293:     my ($domain,$ignore_cache) = @_;
                   2294:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2295:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2296:     unless ($ignore_cache) {
                   2297:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2298:         if (defined($cached)) {
                   2299:             if (ref($result) eq 'HASH') {
                   2300:                 return %{$result};
                   2301:             }
1.943     raeburn  2302:         }
                   2303:     }
                   2304:     my %domdefaults;
                   2305:     my %domconfig =
1.989     raeburn  2306:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2307:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2308:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2309:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2310:                                   'coursecategories','autoenroll',
                   2311:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2312:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2313:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2314:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2315:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2316:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2317:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2318:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2319:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2320:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2321:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2322:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2323:     } else {
                   2324:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2325:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2326:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2327:     }
1.976     raeburn  2328:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2329:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2330:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2331:         } else {
                   2332:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2333:         }
1.1172.2.6  raeburn  2334:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2335:         foreach my $item (@usertools) {
                   2336:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2337:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2338:             }
                   2339:         }
1.1172.2.29  raeburn  2340:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2341:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2342:         }
1.976     raeburn  2343:     }
1.985     raeburn  2344:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2345:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2346:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2347:         }
                   2348:     }
1.1172.2.9  raeburn  2349:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2350:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2351:     }
1.989     raeburn  2352:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2353:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2354:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2355:         }
                   2356:     }
1.1047    raeburn  2357:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2358:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2359:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2360:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2361:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2362:         }
1.1172.2.41  raeburn  2363:         foreach my $type (@coursetypes) {
                   2364:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2365:                 unless ($type eq 'community') {
                   2366:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2367:                 }
                   2368:             }
                   2369:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2370:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2371:             }
1.1172.2.60  raeburn  2372:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2373:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2374:                     $domdefaults{$type.'postsubtimeout'} =
                   2375:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2376:                 }
                   2377:             }
1.1172.2.30  raeburn  2378:         }
1.1172.2.67  raeburn  2379:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2380:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2381:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2382:                 if (@clonecodes) {
                   2383:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2384:                 }
                   2385:             }
                   2386:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2387:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2388:         }
1.1172.2.103  raeburn  2389:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2390:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2391:         }
1.1047    raeburn  2392:     }
1.1073    raeburn  2393:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2394:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2395:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2396:         }
                   2397:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2398:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2399:         }
1.1172.2.62  raeburn  2400:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2401:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2402:         }
1.1073    raeburn  2403:     }
1.1172.2.41  raeburn  2404:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2405:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2406:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2407:                             'approval','limit');
                   2408:             foreach my $type (@coursetypes) {
                   2409:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2410:                     my @mgrdc = ();
                   2411:                     foreach my $item (@settings) {
                   2412:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2413:                             push(@mgrdc,$item);
                   2414:                         }
                   2415:                     }
                   2416:                     if (@mgrdc) {
                   2417:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2418:                     }
                   2419:                 }
                   2420:             }
                   2421:         }
                   2422:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2423:             foreach my $type (@coursetypes) {
                   2424:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2425:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2426:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2427:                     }
                   2428:                 }
                   2429:             }
                   2430:         }
                   2431:     }
1.1172.2.46  raeburn  2432:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2433:         $domdefaults{'catauth'} = 'std';
                   2434:         $domdefaults{'catunauth'} = 'std';
                   2435:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2436:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2437:         }
                   2438:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2439:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2440:         }
                   2441:     }
1.1172.2.76  raeburn  2442:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2443:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2444:     }
1.1172.2.89  raeburn  2445:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2446:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2447:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2448:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2449:         }
                   2450:     }
1.1172.2.23  raeburn  2451:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2452:     return %domdefaults;
                   2453: }
                   2454: 
1.1172.2.106  raeburn  2455: sub get_dom_cats {
                   2456:     my ($dom) = @_;
                   2457:     return unless (&domain($dom));
                   2458:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2459:     unless (defined($cached)) {
                   2460:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2461:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2462:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2463:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2464:             } else {
                   2465:                 $cats = {};
                   2466:             }
                   2467:         } else {
                   2468:             $cats = {};
                   2469:         }
                   2470:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2471:     }
                   2472:     return $cats;
                   2473: }
                   2474: 
                   2475: sub get_dom_instcats {
                   2476:     my ($dom) = @_;
                   2477:     return unless (&domain($dom));
                   2478:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2479:     unless (defined($cached)) {
                   2480:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2481:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2482:         if ($totcodes > 0) {
                   2483:             my $caller = 'global';
                   2484:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2485:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2486:                 $instcats = {
                   2487:                                 codes => \%codes,
                   2488:                                 codetitles => \@codetitles,
                   2489:                                 cat_titles => \%cat_titles,
                   2490:                                 cat_order => \%cat_order,
                   2491:                             };
                   2492:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2493:             }
                   2494:         }
                   2495:     }
                   2496:     return $instcats;
                   2497: }
                   2498: 
                   2499: sub retrieve_instcodes {
                   2500:     my ($coursecodes,$dom) = @_;
                   2501:     my $totcodes;
                   2502:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2503:     foreach my $course (keys(%courses)) {
                   2504:         if (ref($courses{$course}) eq 'HASH') {
                   2505:             if ($courses{$course}{'inst_code'} ne '') {
                   2506:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2507:                 $totcodes ++;
                   2508:             }
                   2509:         }
                   2510:     }
                   2511:     return $totcodes;
                   2512: }
                   2513: 
1.1172.2.113  raeburn  2514: # --------------------------------------------- Get domain config for passwords
                   2515: 
                   2516: sub get_passwdconf {
                   2517:     my ($dom) = @_;
                   2518:     my (%passwdconf,$gotconf,$lookup);
                   2519:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2520:     if (defined($cached)) {
                   2521:         if (ref($result) eq 'HASH') {
                   2522:             %passwdconf = %{$result};
                   2523:             $gotconf = 1;
                   2524:         }
                   2525:     }
                   2526:     unless ($gotconf) {
                   2527:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2528:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2529:             %passwdconf = %{$domconfig{'passwords'}};
                   2530:         }
                   2531:         my $cachetime = 24*60*60;
                   2532:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2533:     }
                   2534:     return %passwdconf;
                   2535: }
                   2536: 
1.344     www      2537: # --------------------------------------------------- Assign a key to a student
                   2538: 
                   2539: sub assign_access_key {
1.364     www      2540: #
                   2541: # a valid key looks like uname:udom#comments
                   2542: # comments are being appended
                   2543: #
1.498     www      2544:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2545:     $kdom=
1.620     albertel 2546:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2547:     $knum=
1.620     albertel 2548:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2549:     $cdom=
1.620     albertel 2550:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2551:     $cnum=
1.620     albertel 2552:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2553:     $udom=$env{'user.name'} unless (defined($udom));
                   2554:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2555:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2556:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2557:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2558:                                                   # assigned to this person
                   2559:                                                   # - this should not happen,
1.345     www      2560:                                                   # unless something went wrong
                   2561:                                                   # the first time around
                   2562: # ready to assign
1.364     www      2563:         $logentry=$1.'; '.$logentry;
1.496     www      2564:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2565:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2566: # key now belongs to user
1.346     www      2567: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2568:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2569:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2570:                 return 'ok';
                   2571:             } else {
                   2572:                 return 
                   2573:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2574: 	    }
                   2575:         } else {
                   2576:             return 'error: Could not assign key, try again later.';
                   2577:         }
1.364     www      2578:     } elsif (!$existing{$ckey}) {
1.345     www      2579: # the key does not exist
                   2580: 	return 'error: The key does not exist';
                   2581:     } else {
                   2582: # the key is somebody else's
                   2583: 	return 'error: The key is already in use';
                   2584:     }
1.344     www      2585: }
                   2586: 
1.364     www      2587: # ------------------------------------------ put an additional comment on a key
                   2588: 
                   2589: sub comment_access_key {
                   2590: #
                   2591: # a valid key looks like uname:udom#comments
                   2592: # comments are being appended
                   2593: #
                   2594:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2595:     $cdom=
1.620     albertel 2596:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2597:     $cnum=
1.620     albertel 2598:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2599:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2600:     if ($existing{$ckey}) {
                   2601:         $existing{$ckey}.='; '.$logentry;
                   2602: # ready to assign
1.367     www      2603:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2604:                                                  $cdom,$cnum) eq 'ok') {
                   2605: 	    return 'ok';
                   2606:         } else {
                   2607: 	    return 'error: Count not store comment.';
                   2608:         }
                   2609:     } else {
                   2610: # the key does not exist
                   2611: 	return 'error: The key does not exist';
                   2612:     }
                   2613: }
                   2614: 
1.344     www      2615: # ------------------------------------------------------ Generate a set of keys
                   2616: 
                   2617: sub generate_access_keys {
1.364     www      2618:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2619:     $cdom=
1.620     albertel 2620:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2621:     $cnum=
1.620     albertel 2622:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2623:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2624:     unless (($cdom) && ($cnum)) { return 0; }
                   2625:     if ($number>10000) { return 0; }
                   2626:     sleep(2); # make sure don't get same seed twice
                   2627:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2628:     my $total=0;
                   2629:     for (my $i=1;$i<=$number;$i++) {
                   2630:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2631:                   sprintf("%lx",int(100000*rand)).'-'.
                   2632:                   sprintf("%lx",int(100000*rand));
                   2633:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2634:        $newkey=~s/0/h/g; # and also 0 and O
                   2635:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2636:        if ($existing{$newkey}) {
                   2637:            $i--;
                   2638:        } else {
1.364     www      2639: 	  if (&put('accesskeys',
                   2640:               { $newkey => '# generated '.localtime().
1.620     albertel 2641:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2642:                            '; '.$logentry },
                   2643: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2644:               $total++;
                   2645: 	  }
                   2646:        }
                   2647:     }
1.620     albertel 2648:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2649:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2650:     return $total;
                   2651: }
                   2652: 
                   2653: # ------------------------------------------------------- Validate an accesskey
                   2654: 
                   2655: sub validate_access_key {
                   2656:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2657:     $cdom=
1.620     albertel 2658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2659:     $cnum=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2661:     $udom=$env{'user.domain'} unless (defined($udom));
                   2662:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2663:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2664:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2665: }
                   2666: 
                   2667: # ------------------------------------- Find the section of student in a course
1.652     albertel 2668: sub devalidate_getsection_cache {
                   2669:     my ($udom,$unam,$courseid)=@_;
                   2670:     my $hashid="$udom:$unam:$courseid";
                   2671:     &devalidate_cache_new('getsection',$hashid);
                   2672: }
1.298     matthew  2673: 
1.815     albertel 2674: sub courseid_to_courseurl {
                   2675:     my ($courseid) = @_;
                   2676:     #already url style courseid
                   2677:     return $courseid if ($courseid =~ m{^/});
                   2678: 
                   2679:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2680: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2681: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2682: 	return "/$cdom/$cnum";
                   2683:     }
                   2684: 
                   2685:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2686:     if (exists($courseinfo{'num'})) {
                   2687: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2688:     }
                   2689: 
                   2690:     return undef;
                   2691: }
                   2692: 
1.298     matthew  2693: sub getsection {
                   2694:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2695:     my $cachetime=1800;
1.551     albertel 2696: 
                   2697:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2698:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2699:     if (defined($cached)) { return $result; }
                   2700: 
1.298     matthew  2701:     my %Pending; 
                   2702:     my %Expired;
                   2703:     #
                   2704:     # Each role can either have not started yet (pending), be active, 
                   2705:     #    or have expired.
                   2706:     #
                   2707:     # If there is an active role, we are done.
                   2708:     #
                   2709:     # If there is more than one role which has not started yet, 
                   2710:     #     choose the one which will start sooner
                   2711:     # If there is one role which has not started yet, return it.
                   2712:     #
                   2713:     # If there is more than one expired role, choose the one which ended last.
                   2714:     # If there is a role which has expired, return it.
                   2715:     #
1.815     albertel 2716:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2717:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2718:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2719:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2720:         my $section=$1;
                   2721:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2722:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2723:         my $now=time;
1.548     albertel 2724:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2725:             $Expired{$end}=$section;
                   2726:             next;
                   2727:         }
1.548     albertel 2728:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2729:             $Pending{$start}=$section;
                   2730:             next;
                   2731:         }
1.599     albertel 2732:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2733:     }
                   2734:     #
                   2735:     # Presumedly there will be few matching roles from the above
                   2736:     # loop and the sorting time will be negligible.
                   2737:     if (scalar(keys(%Pending))) {
                   2738:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2739:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2740:     } 
                   2741:     if (scalar(keys(%Expired))) {
                   2742:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2743:         my $time = pop(@sorted);
1.599     albertel 2744:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2745:     }
1.599     albertel 2746:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2747: }
1.70      www      2748: 
1.599     albertel 2749: sub save_cache {
                   2750:     &purge_remembered();
1.722     albertel 2751:     #&Apache::loncommon::validate_page();
1.620     albertel 2752:     undef(%env);
1.780     albertel 2753:     undef($env_loaded);
1.599     albertel 2754: }
1.452     albertel 2755: 
1.599     albertel 2756: my $to_remember=-1;
                   2757: my %remembered;
                   2758: my %accessed;
                   2759: my $kicks=0;
                   2760: my $hits=0;
1.849     albertel 2761: sub make_key {
                   2762:     my ($name,$id) = @_;
1.872     albertel 2763:     if (length($id) > 65 
                   2764: 	&& length(&escape($id)) > 200) {
                   2765: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2766:     }
1.849     albertel 2767:     return &escape($name.':'.$id);
                   2768: }
                   2769: 
1.599     albertel 2770: sub devalidate_cache_new {
                   2771:     my ($name,$id,$debug) = @_;
                   2772:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2773:     my $remembered_id=$name.':'.$id;
1.849     albertel 2774:     $id=&make_key($name,$id);
1.599     albertel 2775:     $memcache->delete($id);
1.1172.2.81  raeburn  2776:     delete($remembered{$remembered_id});
                   2777:     delete($accessed{$remembered_id});
1.599     albertel 2778: }
                   2779: 
                   2780: sub is_cached_new {
                   2781:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2782:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2783:                                      # keys in %remembered hash, which persists for
                   2784:                                      # duration of request (no restriction on key length).
                   2785:     if (exists($remembered{$remembered_id})) {
                   2786: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2787: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2788: 	$hits++;
1.1172.2.81  raeburn  2789: 	return ($remembered{$remembered_id},1);
1.599     albertel 2790:     }
1.1172.2.81  raeburn  2791:     $id=&make_key($name,$id);
1.599     albertel 2792:     my $value = $memcache->get($id);
                   2793:     if (!(defined($value))) {
                   2794: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2795: 	return (undef,undef);
1.416     albertel 2796:     }
1.599     albertel 2797:     if ($value eq '__undef__') {
                   2798: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2799: 	$value=undef;
                   2800:     }
1.1172.2.81  raeburn  2801:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2802:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2803:     return ($value,1);
                   2804: }
                   2805: 
                   2806: sub do_cache_new {
                   2807:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2808:     my $remembered_id=$name.':'.$id;
1.849     albertel 2809:     $id=&make_key($name,$id);
1.599     albertel 2810:     my $setvalue=$value;
                   2811:     if (!defined($setvalue)) {
                   2812: 	$setvalue='__undef__';
                   2813:     }
1.623     albertel 2814:     if (!defined($time) ) {
                   2815: 	$time=600;
                   2816:     }
1.599     albertel 2817:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2818:     my $result = $memcache->set($id,$setvalue,$time);
                   2819:     if (! $result) {
1.872     albertel 2820: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2821: 	$memcache->disconnect_all();
1.872     albertel 2822:     }
1.600     albertel 2823:     # need to make a copy of $value
1.1172.2.81  raeburn  2824:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2825:     return $value;
                   2826: }
                   2827: 
                   2828: sub make_room {
1.1172.2.81  raeburn  2829:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2830: 
1.1172.2.81  raeburn  2831:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2832:                                     : $value;
1.599     albertel 2833:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2834:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2835:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2836:     my $to_kick;
                   2837:     my $max_time=0;
                   2838:     foreach my $other (keys(%accessed)) {
                   2839: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2840: 	    $to_kick=$other;
                   2841: 	    $max_time=&tv_interval($accessed{$other});
                   2842: 	}
                   2843:     }
                   2844:     delete($remembered{$to_kick});
                   2845:     delete($accessed{$to_kick});
                   2846:     $kicks++;
                   2847:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2848:     return;
                   2849: }
                   2850: 
1.599     albertel 2851: sub purge_remembered {
1.604     albertel 2852:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2853:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2854:     undef(%remembered);
                   2855:     undef(%accessed);
1.428     albertel 2856: }
1.70      www      2857: # ------------------------------------- Read an entry from a user's environment
                   2858: 
                   2859: sub userenvironment {
                   2860:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2861:     my $items;
                   2862:     foreach my $item (@what) {
                   2863:         $items.=&escape($item).'&';
                   2864:     }
                   2865:     $items=~s/\&$//;
1.70      www      2866:     my %returnhash=();
1.1009    raeburn  2867:     my $uhome = &homeserver($unam,$udom);
                   2868:     unless ($uhome eq 'no_host') {
                   2869:         my @answer=split(/\&/, 
                   2870:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2871:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2872:             return %returnhash;
                   2873:         }
1.1009    raeburn  2874:         my $i;
                   2875:         for ($i=0;$i<=$#what;$i++) {
                   2876: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2877:         }
1.70      www      2878:     }
                   2879:     return %returnhash;
1.1       albertel 2880: }
                   2881: 
1.617     albertel 2882: # ---------------------------------------------------------- Get a studentphoto
                   2883: sub studentphoto {
                   2884:     my ($udom,$unam,$ext) = @_;
                   2885:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2886:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2887:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2888:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2889:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2890:             } else {
                   2891:                 my ($result,$perm_reqd)=
1.707     albertel 2892: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2893:                 if ($result eq 'ok') {
                   2894:                     if (!($perm_reqd eq 'yes')) {
                   2895:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2896:                     }
                   2897:                 }
                   2898:             }
                   2899:         }
                   2900:     } else {
                   2901:         my ($result,$perm_reqd) = 
1.707     albertel 2902: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2903:         if ($result eq 'ok') {
                   2904:             if (!($perm_reqd eq 'yes')) {
                   2905:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2906:             }
                   2907:         }
                   2908:     }
                   2909:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2910: }
                   2911: 
                   2912: sub retrievestudentphoto {
                   2913:     my ($udom,$unam,$ext,$type) = @_;
                   2914:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2915:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2916:     if ($ret eq 'ok') {
                   2917:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2918:         if ($type eq 'thumbnail') {
                   2919:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2920:         }
                   2921:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2922:         return $tokenurl;
                   2923:     } else {
                   2924:         if ($type eq 'thumbnail') {
                   2925:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2926:         } else { 
                   2927:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2928:         }
1.617     albertel 2929:     }
                   2930: }
                   2931: 
1.263     www      2932: # -------------------------------------------------------------------- New chat
                   2933: 
                   2934: sub chatsend {
1.724     raeburn  2935:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2936:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2937:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2938:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2939:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2940: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2941: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2942: }
                   2943: 
                   2944: # ------------------------------------------ Find current version of a resource
                   2945: 
                   2946: sub getversion {
                   2947:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2948:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2949:     return &currentversion(&filelocation('',$fname));
                   2950: }
                   2951: 
                   2952: sub currentversion {
                   2953:     my $fname=shift;
                   2954:     my $author=$fname;
                   2955:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2956:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2957:     my $home=&homeserver($uname,$udom);
1.292     www      2958:     if ($home eq 'no_host') { 
                   2959:         return -1; 
                   2960:     }
1.1112    www      2961:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2962:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2963: 	return -1;
                   2964:     }
1.1112    www      2965:     return $answer;
1.263     www      2966: }
                   2967: 
1.1111    www      2968: #
                   2969: # Return special version number of resource if set by override, empty otherwise
                   2970: #
                   2971: sub usedversion {
                   2972:     my $fname=shift;
                   2973:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2974:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2975:     if ($urlversion) { return $urlversion; }
                   2976:     return '';
                   2977: }
                   2978: 
1.1       albertel 2979: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2980: 
1.1       albertel 2981: sub subscribe {
                   2982:     my $fname=shift;
1.761     raeburn  2983:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2984:     $fname=~s/[\n\r]//g;
1.1       albertel 2985:     my $author=$fname;
                   2986:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2987:     my ($udom,$uname)=split(/\//,$author);
                   2988:     my $home=homeserver($uname,$udom);
1.335     albertel 2989:     if ($home eq 'no_host') {
                   2990:         return 'not_found';
1.1       albertel 2991:     }
                   2992:     my $answer=reply("sub:$fname",$home);
1.64      www      2993:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2994: 	$answer.=' by '.$home;
                   2995:     }
1.1       albertel 2996:     return $answer;
                   2997: }
                   2998:     
1.8       www      2999: # -------------------------------------------------------------- Replicate file
                   3000: 
                   3001: sub repcopy {
                   3002:     my $filename=shift;
1.23      www      3003:     $filename=~s/\/+/\//g;
1.1142    raeburn  3004:     my $londocroot = $perlvar{'lonDocRoot'};
                   3005:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3006:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3007:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3008: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3009: 	return &repcopy_userfile($filename);
                   3010:     }
1.532     albertel 3011:     $filename=~s/[\n\r]//g;
1.8       www      3012:     my $transname="$filename.in.transfer";
1.828     www      3013: # FIXME: this should flock
1.607     raeburn  3014:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3015:     my $remoteurl=subscribe($filename);
1.64      www      3016:     if ($remoteurl =~ /^con_lost by/) {
                   3017: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3018:            return 'unavailable';
1.8       www      3019:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3020: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3021: 	   return 'not_found';
1.64      www      3022:     } elsif ($remoteurl =~ /^rejected by/) {
                   3023: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3024:            return 'forbidden';
1.20      www      3025:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3026:            return 'ok';
1.8       www      3027:     } else {
1.290     www      3028:         my $author=$filename;
                   3029:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3030:         my ($udom,$uname)=split(/\//,$author);
                   3031:         my $home=homeserver($uname,$udom);
                   3032:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3033:            my @parts=split(/\//,$filename);
                   3034:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3035:            if ($path ne "$londocroot/res") {
1.8       www      3036:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3037: 	       return 'bad_request';
1.8       www      3038:            }
                   3039:            my $count;
                   3040:            for ($count=5;$count<$#parts;$count++) {
                   3041:                $path.="/$parts[$count]";
                   3042:                if ((-e $path)!=1) {
                   3043: 		   mkdir($path,0777);
                   3044:                }
                   3045:            }
                   3046:            my $ua=new LWP::UserAgent;
                   3047:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3048:            my $response=$ua->request($request,$transname);
                   3049:            if ($response->is_error()) {
                   3050: 	       unlink($transname);
                   3051:                my $message=$response->status_line;
1.672     albertel 3052:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3053:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3054:                return 'unavailable';
1.8       www      3055:            } else {
1.16      www      3056: 	       if ($remoteurl!~/\.meta$/) {
                   3057:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3058:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3059:                   if ($mresponse->is_error()) {
                   3060: 		      unlink($filename.'.meta');
                   3061:                       &logthis(
1.672     albertel 3062:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3063:                   }
                   3064: 	       }
1.8       www      3065:                rename($transname,$filename);
1.607     raeburn  3066:                return 'ok';
1.8       www      3067:            }
1.290     www      3068:        }
1.8       www      3069:     }
1.330     www      3070: }
                   3071: 
1.1172.2.124! raeburn  3072: # ------------------------------------------------- Unsubscribe from a resource
        !          3073: 
        !          3074: sub unsubscribe {
        !          3075:     my ($fname) = @_;
        !          3076:     my $answer;
        !          3077:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
        !          3078:     $fname=~s/[\n\r]//g;
        !          3079:     my $author=$fname;
        !          3080:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
        !          3081:     my ($udom,$uname)=split(/\//,$author);
        !          3082:     my $home=homeserver($uname,$udom);
        !          3083:     if ($home eq 'no_host') {
        !          3084:         $answer = 'no_host';
        !          3085:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
        !          3086:         $answer = 'home';
        !          3087:     } else {
        !          3088:         my $defdom = $perlvar{'lonDefDomain'};
        !          3089:         if (&will_trust('content',$defdom,$udom)) {
        !          3090:             $answer = reply("unsub:$fname",$home);
        !          3091:         } else {
        !          3092:             $answer = 'untrusted';
        !          3093:         }
        !          3094:     }
        !          3095:     return $answer;
        !          3096: }
        !          3097: 
1.330     www      3098: # ------------------------------------------------ Get server side include body
                   3099: sub ssi_body {
1.381     albertel 3100:     my ($filelink,%form)=@_;
1.606     matthew  3101:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3102:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3103:     }
1.953     www      3104:     my $output='';
                   3105:     my $response;
1.980     raeburn  3106:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3107:        ($output,$response)=&externalssi($filelink);
1.953     www      3108:     } else {
1.1004    droeschl 3109:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3110:        $filelink .= 'inhibitmenu=yes';
1.953     www      3111:        ($output,$response)=&ssi($filelink,%form);
                   3112:     }
1.778     albertel 3113:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3114:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3115:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3116:     if (wantarray) {
                   3117:         return ($output, $response);
                   3118:     } else {
                   3119:         return $output;
                   3120:     }
1.8       www      3121: }
                   3122: 
1.15      www      3123: # --------------------------------------------------------- Server Side Include
                   3124: 
1.782     albertel 3125: sub absolute_url {
                   3126:     my ($host_name) = @_;
                   3127:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3128:     if ($host_name eq '') {
                   3129: 	$host_name = $ENV{'SERVER_NAME'};
                   3130:     }
                   3131:     return $protocol.$host_name;
                   3132: }
                   3133: 
1.942     foxr     3134: #
                   3135: #   Server side include.
                   3136: # Parameters:
                   3137: #  fn     Possibly encrypted resource name/id.
                   3138: #  form   Hash that describes how the rendering should be done
                   3139: #         and other things.
1.944     foxr     3140: # Returns:
1.950     raeburn  3141: #   Scalar context: The content of the response.
                   3142: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3143: #     
1.15      www      3144: sub ssi {
                   3145: 
1.944     foxr     3146:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3147:     my ($request,$response);
1.711     albertel 3148: 
                   3149:     $form{'no_update_last_known'}=1;
1.895     albertel 3150:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3151:     if (%form) {
1.782     albertel 3152:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3153:       $request->content(join('&',map {
                   3154:             my $name = escape($_);
                   3155:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3156:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3157:             : &escape($form{$_}) );
                   3158:         } keys(%form)));
1.23      www      3159:     } else {
1.782     albertel 3160:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3161:     }
                   3162: 
1.15      www      3163:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3164: 
1.1172.2.101  raeburn  3165:     if (($env{'request.course.id'}) &&
                   3166:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3167:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3168:         ($form{'grade_symb'} ne '') &&
                   3169:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3170:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3171:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3172:             my $ua=new LWP::UserAgent;
                   3173:             $ua->local_address('127.0.0.1');
                   3174:             $response = $ua->request($request);
                   3175:         } else {
                   3176:             {
                   3177:                 require LWP::Protocol::http;
                   3178:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3179:                 my $ua=new LWP::UserAgent;
                   3180:                 $response = $ua->request($request);
                   3181:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3182:             }
                   3183:         }
                   3184:     } else {
                   3185:         my $ua=new LWP::UserAgent;
                   3186:         $response = $ua->request($request);
                   3187:     }
1.944     foxr     3188:     if (wantarray) {
1.1172.2.3  raeburn  3189: 	return ($response->content, $response);
1.944     foxr     3190:     } else {
1.1172.2.3  raeburn  3191: 	return $response->content;
1.942     foxr     3192:     }
1.324     www      3193: }
                   3194: 
                   3195: sub externalssi {
                   3196:     my ($url)=@_;
                   3197:     my $ua=new LWP::UserAgent;
                   3198:     my $request=new HTTP::Request('GET',$url);
                   3199:     my $response=$ua->request($request);
1.954     raeburn  3200:     if (wantarray) {
                   3201:         return ($response->content, $response);
                   3202:     } else {
                   3203:         return $response->content;
                   3204:     }
1.15      www      3205: }
1.254     www      3206: 
1.1172.2.98  raeburn  3207: # If the local copy of a replicated resource is outdated, trigger a
                   3208: # connection from the homeserver to flush the delayed queue. If no update
                   3209: # happens, remove local copies of outdated resource (and corresponding
                   3210: # metadata file).
                   3211: 
                   3212: sub remove_stale_resfile {
                   3213:     my ($url) = @_;
                   3214:     my $removed;
                   3215:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3216:         my $audom = $1;
                   3217:         my $auname = $2;
                   3218:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3219:             my $homeserver = &homeserver($auname,$audom);
                   3220:             unless (($homeserver eq 'no_host') ||
                   3221:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3222:                 my $fname = &filelocation('',$url);
                   3223:                 if (-e $fname) {
                   3224:                     my $hostname = &hostname($homeserver);
                   3225:                     if ($hostname) {
1.1172.2.120  raeburn  3226:                         my $protocol = $protocol{$homeserver};
                   3227:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3228:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3229:                         my $ua=new LWP::UserAgent;
                   3230:                         $ua->timeout(5);
1.1172.2.98  raeburn  3231:                         my $request=new HTTP::Request('HEAD',$uri);
                   3232:                         my $response=$ua->request($request);
                   3233:                         if ($response->is_success()) {
                   3234:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3235:                             my $locmodtime = (stat($fname))[9];
                   3236:                             if ($locmodtime < $remmodtime) {
                   3237:                                 my $stale;
                   3238:                                 my $answer = &reply('pong',$homeserver);
                   3239:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3240:                                     sleep(0.2);
                   3241:                                     $locmodtime = (stat($fname))[9];
                   3242:                                     if ($locmodtime < $remmodtime) {
                   3243:                                         my $posstransfer = $fname.'.in.transfer';
                   3244:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3245:                                             $removed = 1;
                   3246:                                         } else {
                   3247:                                             $stale = 1;
                   3248:                                         }
                   3249:                                     } else {
                   3250:                                         $removed = 1;
                   3251:                                     }
                   3252:                                 } else {
                   3253:                                     $stale = 1;
                   3254:                                 }
                   3255:                                 if ($stale) {
1.1172.2.124! raeburn  3256:                                     if (unlink($fname)) {
        !          3257:                                         if ($uri!~/\.meta$/) {
        !          3258:                                             if (-e $fname.'.meta') {
        !          3259:                                                 unlink($fname.'.meta');
        !          3260:                                             }
        !          3261:                                         }
        !          3262:                                         my $unsubresult = &unsubscribe($fname);
        !          3263:                                         unless ($unsubresult eq 'ok') {
        !          3264:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
        !          3265:                                         }
        !          3266:                                         $removed = 1;
1.1172.2.98  raeburn  3267:                                     }
                   3268:                                 }
                   3269:                             }
                   3270:                         }
                   3271:                     }
                   3272:                 }
                   3273:             }
                   3274:         }
                   3275:     }
                   3276:     return $removed;
                   3277: }
                   3278: 
1.492     albertel 3279: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3280: 
                   3281: sub allowuploaded {
                   3282:     my ($srcurl,$url)=@_;
                   3283:     $url=&clutter(&declutter($url));
                   3284:     my $dir=$url;
                   3285:     $dir=~s/\/[^\/]+$//;
                   3286:     my %httpref=();
                   3287:     my $httpurl=&hreflocation('',$url);
                   3288:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3289:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3290: }
1.477     raeburn  3291: 
1.1172.2.13  raeburn  3292: #
                   3293: # Determine if the current user should be able to edit a particular resource,
                   3294: # when viewing in course context.
                   3295: # (a) When viewing resource used to determine if "Edit" item is included in
                   3296: #     Functions.
                   3297: # (b) When displaying folder contents in course editor, used to determine if
                   3298: #     "Edit" link will be displayed alongside resource.
                   3299: #
                   3300: #  input: six args -- filename (decluttered), course number, course domain,
                   3301: #                   url, symb (if registered) and group (if this is a group
                   3302: #                   item -- e.g., bulletin board, group page etc.).
                   3303: #  output: array of five scalars --
                   3304: #          $cfile -- url for file editing if editable on current server
                   3305: #          $home -- homeserver of resource (i.e., for author if published,
                   3306: #                                           or course if uploaded.).
                   3307: #          $switchserver --  1 if server switch will be needed.
                   3308: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3309: #          $forceview -- 1 if icon/link should be to go to view mode
                   3310: #
                   3311: 
                   3312: sub can_edit_resource {
                   3313:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3314:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3315: #
                   3316: # For aboutme pages user can only edit his/her own.
                   3317: #
                   3318:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3319:         my ($sdom,$sname) = ($1,$2);
                   3320:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3321:             $home = $env{'user.home'};
                   3322:             $cfile = $resurl;
                   3323:             if ($env{'form.forceedit'}) {
                   3324:                 $forceview = 1;
                   3325:             } else {
                   3326:                 $forceedit = 1;
                   3327:             }
                   3328:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3329:         } else {
                   3330:             return;
                   3331:         }
                   3332:     }
                   3333: 
                   3334:     if ($env{'request.course.id'}) {
                   3335:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3336:         if ($group ne '') {
                   3337: # if this is a group homepage or group bulletin board, check group privs
                   3338:             my $allowed = 0;
                   3339:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3340:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3341:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3342:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3343:                     $allowed = 1;
                   3344:                 }
                   3345:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3346:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3347:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3348:                     $allowed = 1;
                   3349:                 }
                   3350:             }
                   3351:             if ($allowed) {
                   3352:                 $home=&homeserver($cnum,$cdom);
                   3353:                 if ($env{'form.forceedit'}) {
                   3354:                     $forceview = 1;
                   3355:                 } else {
                   3356:                     $forceedit = 1;
                   3357:                 }
                   3358:                 $cfile = $resurl;
                   3359:             } else {
                   3360:                 return;
                   3361:             }
                   3362:         } else {
1.1172.2.15  raeburn  3363:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3364:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3365:                     return;
                   3366:                 }
                   3367:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3368: #
                   3369: # No edit allowed where CC has switched to student role.
                   3370: #
                   3371:                 return;
                   3372:             }
                   3373:         }
                   3374:     }
                   3375: 
                   3376:     if ($file ne '') {
                   3377:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3378:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3379:                 $uploaded = 1;
                   3380:                 $incourse = 1;
                   3381:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3382:                     $cfile = &hreflocation('',$file);
                   3383:                     if ($env{'form.forceedit'}) {
                   3384:                         $forceview = 1;
                   3385:                     } else {
                   3386:                         $forceedit = 1;
                   3387:                     }
                   3388:                 }
                   3389:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3390:                 $incourse = 1;
                   3391:                 if ($env{'form.forceedit'}) {
                   3392:                     $forceview = 1;
                   3393:                 } else {
                   3394:                     $forceedit = 1;
                   3395:                 }
                   3396:                 $cfile = $resurl;
                   3397:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3398:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3399:                     $incourse = 1;
                   3400:                     if ($env{'form.forceedit'}) {
                   3401:                         $forceview = 1;
                   3402:                     } else {
                   3403:                         $forceedit = 1;
                   3404:                     }
                   3405:                     $cfile = $resurl;
                   3406:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3407:                     $incourse = 1;
                   3408:                     $cfile = $resurl.'/smpedit';
                   3409:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3410:                     $incourse = 1;
                   3411:                     if ($env{'form.forceedit'}) {
                   3412:                         $forceview = 1;
                   3413:                     } else {
                   3414:                         $forceedit = 1;
                   3415:                     }
                   3416:                     $cfile = $resurl;
1.1172.2.122  raeburn  3417:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3418:                     my ($map,$id,$res) = &decode_symb($symb);
                   3419:                     if ($map =~ /\.page$/) {
                   3420:                         $incourse = 1;
                   3421:                         if ($env{'form.forceedit'}) {
                   3422:                             $forceview = 1;
                   3423:                             $cfile = $map;
                   3424:                         } else {
                   3425:                             $forceedit = 1;
                   3426:                             $cfile =  '/adm/wrapper'.$resurl;
                   3427:                         }
                   3428:                     }
1.1172.2.15  raeburn  3429:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3430:                     $incourse = 1;
                   3431:                     if ($env{'form.forceedit'}) {
                   3432:                         $forceview = 1;
                   3433:                     } else {
                   3434:                         $forceedit = 1;
                   3435:                     }
                   3436:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3437:                 }
                   3438:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3439:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3440:                 if (&is_on_map($template)) {
                   3441:                     $incourse = 1;
                   3442:                     $forceview = 1;
                   3443:                     $cfile = $template;
                   3444:                 }
                   3445:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3446:                 $incourse = 1;
                   3447:                 if ($env{'form.forceedit'}) {
                   3448:                     $forceview = 1;
                   3449:                 } else {
                   3450:                     $forceedit = 1;
                   3451:                 }
                   3452:                 $cfile = $resurl;
1.1172.2.13  raeburn  3453:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3454:                 $incourse = 1;
                   3455:                 $forceview = 1;
                   3456:                 if ($symb) {
                   3457:                     my ($map,$id,$res)=&decode_symb($symb);
                   3458:                     $env{'request.symb'} = $symb;
                   3459:                     $cfile = &clutter($res);
                   3460:                 } else {
                   3461:                     $cfile = $env{'form.suppurl'};
                   3462:                     $cfile =~ s{^http://}{};
                   3463:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3464:                 }
1.1172.2.31  raeburn  3465:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3466:                 if ($env{'form.forceedit'}) {
                   3467:                     $forceview = 1;
                   3468:                 } else {
                   3469:                     $forceedit = 1;
                   3470:                 }
                   3471:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3472:             }
                   3473:         }
                   3474:         if ($uploaded || $incourse) {
                   3475:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3476:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3477:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3478:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3479:             # Check that the user has permission to edit this resource
                   3480:             my $setpriv = 1;
                   3481:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3482:             if (defined($cfudom)) {
                   3483:                 $home=&homeserver($cfuname,$cfudom);
                   3484:                 $cfile=$file;
                   3485:             }
                   3486:         }
                   3487:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3488:             (($home ne '') && ($home ne 'no_host'))) {
                   3489:             my @ids=&current_machine_ids();
                   3490:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3491:                 $switchserver=1;
                   3492:             }
                   3493:         }
                   3494:     }
                   3495:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3496: }
                   3497: 
                   3498: sub is_course_upload {
                   3499:     my ($file,$cnum,$cdom) = @_;
                   3500:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3501:     $uploadpath =~ s{^\/}{};
                   3502:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3503:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3504:         return 1;
                   3505:     }
                   3506:     return;
                   3507: }
                   3508: 
                   3509: sub in_course {
                   3510:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3511:     if ($hideprivileged) {
                   3512:         my $skipuser;
1.1172.2.23  raeburn  3513:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3514:         my @possdoms = ($cdom);
                   3515:         if ($coursehash{'checkforpriv'}) {
                   3516:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3517:         }
                   3518:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3519:             $skipuser = 1;
                   3520:             if ($coursehash{'nothideprivileged'}) {
                   3521:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3522:                     my $user;
                   3523:                     if ($item =~ /:/) {
                   3524:                         $user = $item;
                   3525:                     } else {
                   3526:                         $user = join(':',split(/[\@]/,$item));
                   3527:                     }
                   3528:                     if ($user eq $uname.':'.$udom) {
                   3529:                         undef($skipuser);
                   3530:                         last;
                   3531:                     }
                   3532:                 }
                   3533:             }
                   3534:             if ($skipuser) {
                   3535:                 return 0;
                   3536:             }
                   3537:         }
                   3538:     }
                   3539:     $type ||= 'any';
                   3540:     if (!defined($cdom) || !defined($cnum)) {
                   3541:         my $cid  = $env{'request.course.id'};
                   3542:         $cdom = $env{'course.'.$cid.'.domain'};
                   3543:         $cnum = $env{'course.'.$cid.'.num'};
                   3544:     }
                   3545:     my $typesref;
                   3546:     if (($type eq 'any') || ($type eq 'all')) {
                   3547:         $typesref = ['active','previous','future'];
                   3548:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3549:         $typesref = [$type];
                   3550:     }
                   3551:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3552:                               $typesref,undef,[$cdom]);
                   3553:     my ($tmp) = keys(%roles);
                   3554:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3555:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3556:     if (@course_roles > 0) {
                   3557:         return 1;
                   3558:     }
                   3559:     return 0;
                   3560: }
                   3561: 
1.478     albertel 3562: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3563: # input: action, courseID, current domain, intended
1.637     raeburn  3564: #        path to file, source of file, instruction to parse file for objects,
                   3565: #        ref to hash for embedded objects,
                   3566: #        ref to hash for codebase of java objects.
1.1095    raeburn  3567: #        reference to scalar to accommodate mime type determined
                   3568: #          from File::MMagic if $parser = parse.
1.637     raeburn  3569: #
1.485     raeburn  3570: # output: url to file (if action was uploaddoc), 
                   3571: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3572: #
1.478     albertel 3573: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3574: # course.
1.477     raeburn  3575: #
1.478     albertel 3576: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3577: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3578: #          course's home server.
1.477     raeburn  3579: #
1.478     albertel 3580: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3581: #          be copied from $source (current location) to 
                   3582: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3583: #         and will then be copied to
                   3584: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3585: #         course's home server.
1.485     raeburn  3586: #
1.481     raeburn  3587: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3588: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3589: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3590: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3591: #         in course's home server.
1.637     raeburn  3592: #
1.477     raeburn  3593: 
                   3594: sub process_coursefile {
1.1095    raeburn  3595:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3596:         $mimetype)=@_;
1.477     raeburn  3597:     my $fetchresult;
1.638     albertel 3598:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3599:     if ($action eq 'propagate') {
1.638     albertel 3600:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3601: 			     $home);
1.481     raeburn  3602:     } else {
1.477     raeburn  3603:         my $fpath = '';
                   3604:         my $fname = $file;
1.478     albertel 3605:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3606:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3607:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3608:         if ($action eq 'copy') {
                   3609:             if ($source eq '') {
                   3610:                 $fetchresult = 'no source file';
                   3611:                 return $fetchresult;
                   3612:             } else {
                   3613:                 my $destination = $filepath.'/'.$fname;
                   3614:                 rename($source,$destination);
                   3615:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3616:                                  $home);
1.481     raeburn  3617:             }
                   3618:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3619:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3620:             print $fh $env{'form.'.$source};
1.481     raeburn  3621:             close($fh);
1.637     raeburn  3622:             if ($parser eq 'parse') {
1.1024    raeburn  3623:                 my $mm = new File::MMagic;
1.1095    raeburn  3624:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3625:                 if ($type eq 'text/html') {
1.1024    raeburn  3626:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3627:                     unless ($parse_result eq 'ok') {
                   3628:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3629:                     }
1.637     raeburn  3630:                 }
1.1095    raeburn  3631:                 if (ref($mimetype)) {
                   3632:                     $$mimetype = $type;
                   3633:                 } 
1.637     raeburn  3634:             }
1.477     raeburn  3635:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3636:                                  $home);
1.481     raeburn  3637:             if ($fetchresult eq 'ok') {
                   3638:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3639:             } else {
                   3640:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3641:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3642:                 return '/adm/notfound.html';
                   3643:             }
1.477     raeburn  3644:         }
                   3645:     }
1.485     raeburn  3646:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3647:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3648:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3649:     }
                   3650:     return $fetchresult;
                   3651: }
                   3652: 
1.637     raeburn  3653: sub build_filepath {
                   3654:     my ($fpath) = @_;
                   3655:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3656:     unless ($fpath eq '') {
                   3657:         my @parts=split('/',$fpath);
                   3658:         foreach my $part (@parts) {
                   3659:             $filepath.= '/'.$part;
                   3660:             if ((-e $filepath)!=1) {
                   3661:                 mkdir($filepath,0777);
                   3662:             }
                   3663:         }
                   3664:     }
                   3665:     return $filepath;
                   3666: }
                   3667: 
                   3668: sub store_edited_file {
1.638     albertel 3669:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3670:     my $file = $primary_url;
                   3671:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3672:     my $fpath = '';
                   3673:     my $fname = $file;
                   3674:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3675:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3676:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3677:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3678:     print $fh $content;
                   3679:     close($fh);
1.638     albertel 3680:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3681:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3682: 			  $home);
1.637     raeburn  3683:     if ($$fetchresult eq 'ok') {
                   3684:         return '/uploaded/'.$fpath.'/'.$fname;
                   3685:     } else {
1.638     albertel 3686:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3687: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3688:         return '/adm/notfound.html';
                   3689:     }
                   3690: }
                   3691: 
1.531     albertel 3692: sub clean_filename {
1.831     albertel 3693:     my ($fname,$args)=@_;
1.315     www      3694: # Replace Windows backslashes by forward slashes
1.257     www      3695:     $fname=~s/\\/\//g;
1.831     albertel 3696:     if (!$args->{'keep_path'}) {
                   3697:         # Get rid of everything but the actual filename
                   3698: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3699:     }
1.315     www      3700: # Replace spaces by underscores
                   3701:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3702: # Transliterate non-ascii text to ascii
                   3703:     my $lang = &Apache::lonlocal::current_language();
                   3704:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3705: # Replace all other weird characters by nothing
1.831     albertel 3706:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3707: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3708: # numbers
                   3709:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3710:     return $fname;
                   3711: }
1.1172.2.110  raeburn  3712: 
1.1051    raeburn  3713: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3714: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3715: # image with the same aspect ratio as the original, but with dimensions which do 
                   3716: # not exceed $resizewidth and $resizeheight.
                   3717:  
1.984     neumanie 3718: sub resizeImage {
1.1051    raeburn  3719:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3720:     my $ima = Image::Magick->new;
                   3721:     my $resized;
                   3722:     if (-e $img_path) {
                   3723:         $ima->Read($img_path);
                   3724:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3725:             my $width = $ima->Get('width');
                   3726:             my $height = $ima->Get('height');
                   3727:             if ($width > $resizewidth) {
                   3728: 	        my $factor = $width/$resizewidth;
                   3729:                 my $newheight = $height/$factor;
                   3730:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3731:                 $resized = 1;
                   3732:             }
                   3733:         }
                   3734:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3735:             my $width = $ima->Get('width');
                   3736:             my $height = $ima->Get('height');
                   3737:             if ($height > $resizeheight) {
                   3738:                 my $factor = $height/$resizeheight;
                   3739:                 my $newwidth = $width/$factor;
                   3740:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3741:                 $resized = 1;
                   3742:             }
                   3743:         }
                   3744:         if ($resized) {
                   3745:             $ima->Write($img_path);
                   3746:         }
                   3747:     }
                   3748:     return;
1.977     amueller 3749: }
                   3750: 
1.608     albertel 3751: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3752: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3753: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3754: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3755: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3756: #                   if 'coursedoc': upload to the current course
                   3757: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3758: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3759: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3760: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3761: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3762: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3763: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3764: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3765: #        $allfiles - reference to hash for embedded objects
                   3766: #        $codebase - reference to hash for codebase of java objects
                   3767: #        $desuname - username for permanent storage of uploaded file
                   3768: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3769: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3770: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3771: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3772: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3773: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3774: #                    from File::MMagic.
1.858     raeburn  3775: # 
1.686     albertel 3776: # output: url of file in userspace, or error: <message> 
                   3777: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3778: 
1.531     albertel 3779: sub userfileupload {
1.1090    raeburn  3780:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3781:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3782:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3783:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3784:     $fname=&clean_filename($fname);
1.1090    raeburn  3785:     # See if there is anything left
1.257     www      3786:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3787:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3788:     if ($fname =~ /^\./) {
                   3789:         my ($s,$usec) = &gettimeofday();
                   3790:         while (length($usec) < 6) {
                   3791:             $usec = '0'.$usec;
                   3792:         }
                   3793:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3794:     }
1.1090    raeburn  3795:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3796:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3797:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3798:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3799:         my $now = time;
1.1090    raeburn  3800:         my $filepath;
1.1095    raeburn  3801:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3802:              $filepath = 'tmp/helprequests/'.$now;
                   3803:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3804:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3805:                          '_'.$env{'user.domain'}.'/pending';
                   3806:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3807:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3808:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3809:                 $docudom = $destudom;
                   3810:             } else {
                   3811:                 $docudom = $env{'user.domain'};
                   3812:             }
1.1172.2.96  raeburn  3813:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3814:                 $docuname = $destuname;
                   3815:             } else {
                   3816:                 $docuname = $env{'user.name'};
                   3817:             }
                   3818:             if (exists($env{'form.group'})) {
                   3819:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3820:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3821:             }
                   3822:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3823:             if ($context eq 'canceloverwrite') {
                   3824:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3825:                 if (-e  $tempfile) {
                   3826:                     my @info = stat($tempfile);
                   3827:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3828:                         unlink($tempfile);
                   3829:                     }
                   3830:                 }
                   3831:                 return;
1.523     raeburn  3832:             }
                   3833:         }
1.1090    raeburn  3834:         # Create the directory if not present
1.741     raeburn  3835:         my @parts=split(/\//,$filepath);
                   3836:         my $fullpath = $perlvar{'lonDaemons'};
                   3837:         for (my $i=0;$i<@parts;$i++) {
                   3838:             $fullpath .= '/'.$parts[$i];
                   3839:             if ((-e $fullpath)!=1) {
                   3840:                 mkdir($fullpath,0777);
                   3841:             }
                   3842:         }
1.1172.2.96  raeburn  3843:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3844:         print $fh $env{'form.'.$formname};
                   3845:         close($fh);
1.1090    raeburn  3846:         if ($context eq 'existingfile') {
                   3847:             my @info = stat($fullpath.'/'.$fname);
                   3848:             return ($fullpath.'/'.$fname,$info[9]);
                   3849:         } else {
                   3850:             return $fullpath.'/'.$fname;
                   3851:         }
1.523     raeburn  3852:     }
1.995     raeburn  3853:     if ($subdir eq 'scantron') {
                   3854:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3855:     } else {
1.995     raeburn  3856:         $fname="$subdir/$fname";
                   3857:     }
1.1090    raeburn  3858:     if ($context eq 'coursedoc') {
1.638     albertel 3859: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3860: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3861:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3862:             return &finishuserfileupload($docuname,$docudom,
                   3863: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3864: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3865:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3866:         } else {
1.1172.2.21  raeburn  3867:             if ($env{'form.folder'}) {
                   3868:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3869:             }
1.638     albertel 3870:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3871: 				       $fname,$formname,$parser,
1.1095    raeburn  3872: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3873:         }
1.719     banghart 3874:     } elsif (defined($destuname)) {
                   3875:         my $docuname=$destuname;
                   3876:         my $docudom=$destudom;
1.860     raeburn  3877: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3878: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3879:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3880:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3881:     } else {
1.638     albertel 3882:         my $docuname=$env{'user.name'};
                   3883:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3884:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3885:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3886:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3887:         }
1.860     raeburn  3888: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3889: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3890:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3891:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3892:     }
1.271     www      3893: }
                   3894: 
                   3895: sub finishuserfileupload {
1.860     raeburn  3896:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3897:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3898:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3899:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3900:   
1.860     raeburn  3901:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3902:     $file=$fname;
                   3903:     if ($fname=~m|/|) {
                   3904:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3905: 	$path.=$fnamepath.'/';
                   3906:     }
1.259     www      3907:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3908:     my $count;
                   3909:     for ($count=4;$count<=$#parts;$count++) {
                   3910:         $filepath.="/$parts[$count]";
                   3911:         if ((-e $filepath)!=1) {
                   3912: 	    mkdir($filepath,0777);
                   3913:         }
                   3914:     }
1.984     neumanie 3915: 
1.258     www      3916: # Save the file
                   3917:     {
1.1172.2.96  raeburn  3918: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3919: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3920: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3921: 	    return '/adm/notfound.html';
                   3922: 	}
1.1090    raeburn  3923:         if ($context eq 'overwrite') {
1.1117    foxr     3924:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3925:             my $target = $filepath.'/'.$file;
                   3926:             if (-e $source) {
                   3927:                 my @info = stat($source);
                   3928:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3929:                     unless (&File::Copy::move($source,$target)) {
                   3930:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3931:                         return "Moving from $source failed";
                   3932:                     }
                   3933:                 } else {
                   3934:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3935:                 }
                   3936:             } else {
                   3937:                 return "Temporary file: $source missing";
                   3938:             }
                   3939:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3940: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3941: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3942: 	    return '/adm/notfound.html';
                   3943: 	}
1.570     albertel 3944: 	close(FH);
1.1051    raeburn  3945:         if ($resizewidth && $resizeheight) {
                   3946:             my $mm = new File::MMagic;
                   3947:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3948:             if ($mime_type =~ m{^image/}) {
                   3949: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3950:             }  
1.977     amueller 3951: 	}
1.258     www      3952:     }
1.1152    raeburn  3953:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3954:         if (ref($mimetype)) {
                   3955:             if ($$mimetype eq '') {
                   3956:                 my $mm = new File::MMagic;
                   3957:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3958:                 $$mimetype = $type;
                   3959:             }
                   3960:         }
                   3961:     }
1.1172.2.109  raeburn  3962:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3963:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3964:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3965:                                                        $allfiles,$codebase);
                   3966:             unless ($parse_result eq 'ok') {
                   3967:                 &logthis('Failed to parse '.$filepath.$file.
                   3968: 	   	         ' for embedded media: '.$parse_result); 
                   3969:             }
1.637     raeburn  3970:         }
1.1172.2.109  raeburn  3971:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3972:         my $format = $env{'form.scantron_format'};
                   3973:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3974:     }
1.860     raeburn  3975:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3976:         my $input = $filepath.'/'.$file;
                   3977:         my $output = $filepath.'/'.'tn-'.$file;
                   3978:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3979:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3980:         system({$args[0]} @args);
1.860     raeburn  3981:         if (-e $filepath.'/'.'tn-'.$file) {
                   3982:             $fetchthumb  = 1; 
                   3983:         }
                   3984:     }
1.858     raeburn  3985:  
1.259     www      3986: # Notify homeserver to grep it
                   3987: #
1.984     neumanie 3988:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3989:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3990:     if ($fetchresult eq 'ok') {
1.860     raeburn  3991:         if ($fetchthumb) {
                   3992:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3993:             if ($thumbresult ne 'ok') {
                   3994:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3995:                          $docuhome.': '.$thumbresult);
                   3996:             }
                   3997:         }
1.259     www      3998: #
1.258     www      3999: # Return the URL to it
1.494     albertel 4000:         return '/uploaded/'.$path.$file;
1.263     www      4001:     } else {
1.494     albertel 4002:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4003: 		 ': '.$fetchresult);
1.263     www      4004:         return '/adm/notfound.html';
1.858     raeburn  4005:     }
1.493     albertel 4006: }
                   4007: 
1.637     raeburn  4008: sub extract_embedded_items {
1.961     raeburn  4009:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4010:     my @state = ();
1.1164    raeburn  4011:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4012:     my %javafiles = (
                   4013:                       codebase => '',
                   4014:                       code => '',
                   4015:                       archive => ''
                   4016:                     );
                   4017:     my %mediafiles = (
                   4018:                       src => '',
                   4019:                       movie => '',
                   4020:                      );
1.648     raeburn  4021:     my $p;
                   4022:     if ($content) {
                   4023:         $p = HTML::LCParser->new($content);
                   4024:     } else {
1.961     raeburn  4025:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4026:     }
1.641     albertel 4027:     while (my $t=$p->get_token()) {
1.640     albertel 4028: 	if ($t->[0] eq 'S') {
                   4029: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4030: 	    push(@state, $tagname);
1.648     raeburn  4031:             if (lc($tagname) eq 'allow') {
                   4032:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4033:             }
1.640     albertel 4034: 	    if (lc($tagname) eq 'img') {
                   4035: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4036: 	    }
1.886     albertel 4037: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4038:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4039: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4040:                 }
1.886     albertel 4041: 	    }
1.645     raeburn  4042:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4043:                 my $src;
1.645     raeburn  4044:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4045:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4046:                 } else {
1.1164    raeburn  4047:                     if ($attr->{'src'} ne '') {
                   4048:                         $src = $attr->{'src'};
                   4049:                         &add_filetype($allfiles,$src,'src');
                   4050:                     }
                   4051:                 }
                   4052:                 my $text = $p->get_trimmed_text();
                   4053:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4054:                     my @swfargs = split(/,/,$1);
                   4055:                     foreach my $item (@swfargs) {
                   4056:                         $item =~ s/["']//g;
                   4057:                         $item =~ s/^\s+//;
                   4058:                         $item =~ s/\s+$//;
                   4059:                     }
                   4060:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4061:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4062:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4063:                         } else {
                   4064:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4065:                         }
                   4066:                     }
1.645     raeburn  4067:                 }
                   4068:             }
                   4069:             if (lc($tagname) eq 'link') {
                   4070:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4071:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4072:                 }
                   4073:             }
1.640     albertel 4074: 	    if (lc($tagname) eq 'object' ||
                   4075: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4076: 		foreach my $item (keys(%javafiles)) {
                   4077: 		    $javafiles{$item} = '';
                   4078: 		}
1.1164    raeburn  4079:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4080:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4081:                 }
1.640     albertel 4082: 	    }
                   4083: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4084: 		my $name = lc($attr->{'name'});
                   4085: 		foreach my $item (keys(%javafiles)) {
                   4086: 		    if ($name eq $item) {
                   4087: 			$javafiles{$item} = $attr->{'value'};
                   4088: 			last;
                   4089: 		    }
                   4090: 		}
1.1164    raeburn  4091:                 my $pathfrom;
1.640     albertel 4092: 		foreach my $item (keys(%mediafiles)) {
                   4093: 		    if ($name eq $item) {
1.1164    raeburn  4094:                         $pathfrom = $attr->{'value'};
                   4095:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4096: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4097: 			last;
                   4098: 		    }
                   4099: 		}
1.1164    raeburn  4100:                 if ($name eq 'flashvars') {
                   4101:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4102:                 }
                   4103:                 if ($pathfrom ne '') {
                   4104:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4105:                                          $pathfrom);
                   4106:                 }
1.640     albertel 4107: 	    }
                   4108: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4109: 		foreach my $item (keys(%javafiles)) {
                   4110: 		    if ($attr->{$item}) {
                   4111: 			$javafiles{$item} = $attr->{$item};
                   4112: 			last;
                   4113: 		    }
                   4114: 		}
                   4115: 		foreach my $item (keys(%mediafiles)) {
                   4116: 		    if ($attr->{$item}) {
                   4117: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4118: 			last;
                   4119: 		    }
                   4120: 		}
1.1164    raeburn  4121:                 if (lc($tagname) eq 'embed') {
                   4122:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4123:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4124:                                              $attr->{'src'});
                   4125:                     }
                   4126:                 }
1.640     albertel 4127: 	    }
1.1172.2.35  raeburn  4128:             if (lc($tagname) eq 'iframe') {
                   4129:                 my $src = $attr->{'src'} ;
                   4130:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4131:                     &add_filetype($allfiles,$src,'src');
                   4132:                 } elsif ($src =~ m{^/}) {
                   4133:                     if ($env{'request.course.id'}) {
                   4134:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4135:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4136:                         my $url = &hreflocation('',$fullpath);
                   4137:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4138:                             my $relpath = $1;
                   4139:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4140:                                 &add_filetype($allfiles,$1,'src');
                   4141:                             }
                   4142:                         }
                   4143:                     }
                   4144:                 }
                   4145:             }
1.1164    raeburn  4146:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4147:                 pop(@state);
1.1164    raeburn  4148:             }
1.640     albertel 4149: 	} elsif ($t->[0] eq 'E') {
                   4150: 	    my ($tagname) = ($t->[1]);
                   4151: 	    if ($javafiles{'codebase'} ne '') {
                   4152: 		$javafiles{'codebase'} .= '/';
                   4153: 	    }  
                   4154: 	    if (lc($tagname) eq 'applet' ||
                   4155: 		lc($tagname) eq 'object' ||
                   4156: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4157: 		) {
                   4158: 		foreach my $item (keys(%javafiles)) {
                   4159: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4160: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4161: 			&add_filetype($allfiles,$file,$item);
                   4162: 		    }
                   4163: 		}
                   4164: 	    } 
                   4165: 	    pop @state;
                   4166: 	}
                   4167:     }
1.1164    raeburn  4168:     foreach my $id (sort(keys(%flashvars))) {
                   4169:         if ($shockwave{$id} ne '') {
                   4170:             my @pairs = split(/\&/,$flashvars{$id});
                   4171:             foreach my $pair (@pairs) {
                   4172:                 my ($key,$value) = split(/\=/,$pair);
                   4173:                 if ($key eq 'thumb') {
                   4174:                     &add_filetype($allfiles,$value,$key);
                   4175:                 } elsif ($key eq 'content') {
                   4176:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4177:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4178:                     if ($ext ne '') {
                   4179:                         &add_filetype($allfiles,$path.$value,$ext);
                   4180:                     }
                   4181:                 }
                   4182:             }
                   4183:         }
                   4184:     }
1.637     raeburn  4185:     return 'ok';
                   4186: }
                   4187: 
1.639     albertel 4188: sub add_filetype {
                   4189:     my ($allfiles,$file,$type)=@_;
                   4190:     if (exists($allfiles->{$file})) {
                   4191: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4192: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4193: 	}
                   4194:     } else {
                   4195: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4196:     }
                   4197: }
                   4198: 
1.1164    raeburn  4199: sub embedded_dependency {
                   4200:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4201:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4202:         if (($identifier ne '') &&
                   4203:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4204:             ($pathfrom ne '')) {
                   4205:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4206:             foreach my $dep (@{$related->{$identifier}}) {
                   4207:                 &add_filetype($allfiles,$path.$dep,'object');
                   4208:             }
                   4209:         }
                   4210:     }
                   4211:     return;
                   4212: }
                   4213: 
1.1172.2.109  raeburn  4214: sub bubblesheet_converter {
                   4215:     my ($cdom,$fullpath,$config,$format) = @_;
                   4216:     if ((&domain($cdom) ne '') &&
                   4217:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4218:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4219:         my (%csvcols,%csvoptions);
                   4220:         if (ref($config->{'fields'}) eq 'HASH') {
                   4221:             %csvcols = %{$config->{'fields'}};
                   4222:         }
                   4223:         if (ref($config->{'options'}) eq 'HASH') {
                   4224:             %csvoptions = %{$config->{'options'}};
                   4225:         }
                   4226:         my %csvbynum = reverse(%csvcols);
                   4227:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4228:         if (keys(%scantronconf)) {
                   4229:             my %bynum = (
                   4230:                           $scantronconf{CODEstart} => 'CODEstart',
                   4231:                           $scantronconf{IDstart}   => 'IDstart',
                   4232:                           $scantronconf{PaperID}   => 'PaperID',
                   4233:                           $scantronconf{FirstName} => 'FirstName',
                   4234:                           $scantronconf{LastName}  => 'LastName',
                   4235:                           $scantronconf{Qstart}    => 'Qstart',
                   4236:                         );
                   4237:             my @ordered;
                   4238:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4239:                 push(@ordered,$bynum{$item});
                   4240:             }
                   4241:             my %mapstart = (
                   4242:                               CODEstart => 'CODE',
                   4243:                               IDstart   => 'ID',
                   4244:                               PaperID   => 'PaperID',
                   4245:                               FirstName => 'FirstName',
                   4246:                               LastName  => 'LastName',
                   4247:                               Qstart    => 'FirstQuestion',
                   4248:                            );
                   4249:             my %maplength = (
                   4250:                               CODEstart => 'CODElength',
                   4251:                               IDstart   => 'IDlength',
                   4252:                               PaperID   => 'PaperIDlength',
                   4253:                               FirstName => 'FirstNamelength',
                   4254:                               LastName  => 'LastNamelength',
                   4255:             );
                   4256:             if (open(my $fh,'<',$fullpath)) {
                   4257:                 my $output;
                   4258:                 my %lettdig = &letter_to_digits();
                   4259:                 my %diglett = reverse(%lettdig);
                   4260:                 my $numletts = scalar(keys(%lettdig));
                   4261:                 my $num = 0;
                   4262:                 while (my $line=<$fh>) {
                   4263:                     $num ++;
                   4264:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4265:                     $line =~ s{[\r\n]+$}{};
                   4266:                     my %found;
                   4267:                     my @values = split(/,/,$line);
                   4268:                     my ($qstart,$record);
                   4269:                     for (my $i=0; $i<@values; $i++) {
                   4270:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4271:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4272:                             if ($values[$i] eq '') {
                   4273:                                 $values[$i] = $scantronconf{'Qoff'};
                   4274:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4275:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4276:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4277:                                 }
                   4278:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4279:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4280:                                     $values[$i] = $diglett{$values[$i]};
                   4281:                                 }
                   4282:                             } else {
                   4283:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4284:                                     my $digit;
                   4285:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4286:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4287:                                         if ($values[$i] eq 'J') {
                   4288:                                             $digit += $numletts;
                   4289:                                         }
                   4290:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4291:                                         $digit = $values[$i]-1;
                   4292:                                         if ($values[$i] eq '0') {
                   4293:                                             $digit += $numletts;
                   4294:                                         }
                   4295:                                     }
                   4296:                                     my $qval='';
                   4297:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4298:                                         if ($j == $digit) {
                   4299:                                             $qval .= $scantronconf{'Qon'};
                   4300:                                         } else {
                   4301:                                             $qval .= $scantronconf{'Qoff'};
                   4302:                                         }
                   4303:                                     }
                   4304:                                     $values[$i] = $qval;
                   4305:                                 }
                   4306:                             }
                   4307:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4308:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4309:                             }
                   4310:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4311:                             if ($numblank > 0) {
                   4312:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4313:                             }
                   4314:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4315:                                 $qstart = $i;
                   4316:                                 $found{$csvbynum{$i}} = $values[$i];
                   4317:                             } else {
                   4318:                                 $found{'FirstQuestion'} .= $values[$i];
                   4319:                             }
                   4320:                         } elsif (exists($csvbynum{$i})) {
                   4321:                             if ($csvoptions{'rem'}) {
                   4322:                                 $values[$i] =~ s/^\s+//;
                   4323:                             }
                   4324:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4325:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4326:                                     $values[$i] = '0'.$values[$i];
                   4327:                                 }
                   4328:                             }
                   4329:                             $found{$csvbynum{$i}} = $values[$i];
                   4330:                         }
                   4331:                     }
                   4332:                     foreach my $item (@ordered) {
                   4333:                         my $currlength = 1+length($record);
                   4334:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4335:                         if ($numspaces > 0) {
                   4336:                             $record .= (' ' x $numspaces);
                   4337:                         }
                   4338:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4339:                             unless ($item eq 'Qstart') {
                   4340:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4341:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4342:                                 }
                   4343:                             }
                   4344:                             $record .= $found{$mapstart{$item}};
                   4345:                         }
                   4346:                     }
                   4347:                     $output .= "$record\n";
                   4348:                 }
                   4349:                 close($fh);
                   4350:                 if ($output) {
                   4351:                     if (open(my $fh,'>',$fullpath)) {
                   4352:                         print $fh $output;
                   4353:                         close($fh);
                   4354:                     }
                   4355:                 }
                   4356:             }
                   4357:         }
                   4358:         return;
                   4359:     }
                   4360: }
                   4361: 
                   4362: sub letter_to_digits {
                   4363:     my %lettdig = (
                   4364:                     A => 1,
                   4365:                     B => 2,
                   4366:                     C => 3,
                   4367:                     D => 4,
                   4368:                     E => 5,
                   4369:                     F => 6,
                   4370:                     G => 7,
                   4371:                     H => 8,
                   4372:                     I => 9,
                   4373:                     J => 0,
                   4374:                   );
                   4375:     return %lettdig;
                   4376: }
                   4377: 
                   4378: sub get_scantron_config {
                   4379:     my ($which,$cdom) = @_;
                   4380:     my @lines = &get_scantronformat_file($cdom);
                   4381:     my %config;
                   4382:     #FIXME probably should move to XML it has already gotten a bit much now
                   4383:     foreach my $line (@lines) {
                   4384:         my ($name,$descrip)=split(/:/,$line);
                   4385:         if ($name ne $which ) { next; }
                   4386:         chomp($line);
                   4387:         my @config=split(/:/,$line);
                   4388:         $config{'name'}=$config[0];
                   4389:         $config{'description'}=$config[1];
                   4390:         $config{'CODElocation'}=$config[2];
                   4391:         $config{'CODEstart'}=$config[3];
                   4392:         $config{'CODElength'}=$config[4];
                   4393:         $config{'IDstart'}=$config[5];
                   4394:         $config{'IDlength'}=$config[6];
                   4395:         $config{'Qstart'}=$config[7];
                   4396:         $config{'Qlength'}=$config[8];
                   4397:         $config{'Qoff'}=$config[9];
                   4398:         $config{'Qon'}=$config[10];
                   4399:         $config{'PaperID'}=$config[11];
                   4400:         $config{'PaperIDlength'}=$config[12];
                   4401:         $config{'FirstName'}=$config[13];
                   4402:         $config{'FirstNamelength'}=$config[14];
                   4403:         $config{'LastName'}=$config[15];
                   4404:         $config{'LastNamelength'}=$config[16];
                   4405:         $config{'BubblesPerRow'}=$config[17];
                   4406:         last;
                   4407:     }
                   4408:     return %config;
                   4409: }
                   4410: 
                   4411: sub get_scantronformat_file {
                   4412:     my ($cdom) = @_;
                   4413:     if ($cdom eq '') {
                   4414:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4415:     }
                   4416:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4417:     my $gottab = 0;
                   4418:     my @lines;
                   4419:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4420:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4421:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4422:             if ($formatfile ne '-1') {
                   4423:                 @lines = split("\n",$formatfile,-1);
                   4424:                 $gottab = 1;
                   4425:             }
                   4426:         }
                   4427:     }
                   4428:     if (!$gottab) {
                   4429:         my $confname = $cdom.'-domainconfig';
                   4430:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4431:         my $formatfile = &getfile($default);
                   4432:         if ($formatfile ne '-1') {
                   4433:             @lines = split("\n",$formatfile,-1);
                   4434:             $gottab = 1;
                   4435:         }
                   4436:     }
                   4437:     if (!$gottab) {
                   4438:         my @domains = &current_machine_domains();
                   4439:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4440:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4441:                 @lines = <$fh>;
                   4442:                 close($fh);
                   4443:             }
                   4444:         } else {
                   4445:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4446:                 @lines = <$fh>;
                   4447:                 close($fh);
                   4448:             }
                   4449:         }
                   4450:     }
                   4451:     return @lines;
                   4452: }
                   4453: 
1.493     albertel 4454: sub removeuploadedurl {
1.984     neumanie 4455:     my ($url)=@_;	
                   4456:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4457:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4458: }
                   4459: 
                   4460: sub removeuserfile {
                   4461:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4462:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4463:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4464:     if ($result eq 'ok') {	
1.798     raeburn  4465:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4466:             my $metafile = $fname.'.meta';
                   4467:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4468: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4469:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4470:             my $sqlresult = 
1.823     albertel 4471:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4472:                                         'portfolio_metadata',$group,
                   4473:                                         'delete');
1.798     raeburn  4474:         }
                   4475:     }
                   4476:     return $result;
1.257     www      4477: }
1.15      www      4478: 
1.530     albertel 4479: sub mkdiruserfile {
                   4480:     my ($docuname,$docudom,$dir)=@_;
                   4481:     my $home=&homeserver($docuname,$docudom);
                   4482:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4483: }
                   4484: 
1.531     albertel 4485: sub renameuserfile {
                   4486:     my ($docuname,$docudom,$old,$new)=@_;
                   4487:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4488:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4489:                         &escape("$old").':'.&escape("$new"),$home);
                   4490:     if ($result eq 'ok') {
                   4491:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4492:             my $oldmeta = $old.'.meta';
                   4493:             my $newmeta = $new.'.meta';
                   4494:             my $metaresult = 
                   4495:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4496: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4497:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4498:             my $sqlresult = 
1.823     albertel 4499:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4500:                                         'portfolio_metadata',$group,
                   4501:                                         'delete');
1.798     raeburn  4502:         }
                   4503:     }
                   4504:     return $result;
1.531     albertel 4505: }
                   4506: 
1.14      www      4507: # ------------------------------------------------------------------------- Log
                   4508: 
                   4509: sub log {
                   4510:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4511:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4512: }
                   4513: 
                   4514: # ------------------------------------------------------------------ Course Log
1.352     www      4515: #
                   4516: # This routine flushes several buffers of non-mission-critical nature
                   4517: #
1.157     www      4518: 
                   4519: sub flushcourselogs {
1.352     www      4520:     &logthis('Flushing log buffers');
                   4521: #
                   4522: # course logs
                   4523: # This is a log of all transactions in a course, which can be used
                   4524: # for data mining purposes
                   4525: #
                   4526: # It also collects the courseid database, which lists last transaction
                   4527: # times and course titles for all courseids
                   4528: #
                   4529:     my %courseidbuffer=();
1.921     raeburn  4530:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4531:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4532: 		          &escape($courselogs{$crsid}),
                   4533: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4534: 	    delete $courselogs{$crsid};
                   4535:         } else {
                   4536:             &logthis('Failed to flush log buffer for '.$crsid);
                   4537:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4538:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4539:                         " exceeded maximum size, deleting.</font>");
                   4540:                delete $courselogs{$crsid};
                   4541:             }
1.352     www      4542:         }
1.920     raeburn  4543:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4544:             'description' => $coursedescrbuf{$crsid},
                   4545:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4546:             'type'        => $coursetypebuf{$crsid},
                   4547:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4548:         };
1.191     harris41 4549:     }
1.352     www      4550: #
                   4551: # Write course id database (reverse lookup) to homeserver of courses 
                   4552: # Is used in pickcourse
                   4553: #
1.840     albertel 4554:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4555:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4556:                                     $courseidbuffer{$crs_home},
                   4557:                                     $crs_home,'timeonly');
1.352     www      4558:     }
                   4559: #
                   4560: # File accesses
                   4561: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4562: #
1.449     matthew  4563:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4564:         if ($entry =~ /___count$/) {
                   4565:             my ($dom,$name);
1.807     albertel 4566:             ($dom,$name,undef)=
1.811     albertel 4567: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4568:             if (! defined($dom) || $dom eq '' || 
                   4569:                 ! defined($name) || $name eq '') {
1.620     albertel 4570:                 my $cid = $env{'request.course.id'};
                   4571:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4572:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4573:             }
1.450     matthew  4574:             my $value = $accesshash{$entry};
                   4575:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4576:             my %temphash=($url => $value);
1.449     matthew  4577:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4578:             if ($result eq 'ok') {
                   4579:                 delete $accesshash{$entry};
                   4580:             }
                   4581:         } else {
1.811     albertel 4582:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4583:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4584:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4585:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4586:                 delete $accesshash{$entry};
                   4587:             }
1.185     www      4588:         }
1.191     harris41 4589:     }
1.352     www      4590: #
                   4591: # Roles
                   4592: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4593: #
1.800     albertel 4594:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4595:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4596: 	    split(/\:/,$entry);
                   4597:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4598:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4599:                 $rudom,$runame) eq 'ok') {
                   4600: 	    delete $userrolehash{$entry};
                   4601:         }
                   4602:     }
1.662     raeburn  4603: #
1.1172.2.90  raeburn  4604: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4605: #
                   4606:     my %domrolebuffer = ();
1.1000    raeburn  4607:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4608:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4609:         if ($domrolebuffer{$rudom}) {
                   4610:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4611:                       '='.&escape($domainrolehash{$entry});
                   4612:         } else {
                   4613:             $domrolebuffer{$rudom}.=&escape($entry).
                   4614:                       '='.&escape($domainrolehash{$entry});
                   4615:         }
                   4616:         delete $domainrolehash{$entry};
                   4617:     }
                   4618:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4619:         my %servers;
                   4620:         if (defined(&domain($dom,'primary'))) {
                   4621:             my $primary=&domain($dom,'primary');
                   4622:             my $hostname=&hostname($primary);
                   4623:             $servers{$primary} = $hostname;
                   4624:         } else {
                   4625:             %servers = &get_servers($dom,'library');
                   4626:         }
1.841     albertel 4627: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4628: 	    if (&reply('domroleput:'.$dom.':'.
                   4629: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4630: 	        last;
                   4631: 	    } else {
1.841     albertel 4632: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4633: 	    }
1.662     raeburn  4634:         }
                   4635:     }
1.186     www      4636:     $dumpcount++;
1.157     www      4637: }
                   4638: 
                   4639: sub courselog {
                   4640:     my $what=shift;
1.158     www      4641:     $what=time.':'.$what;
1.620     albertel 4642:     unless ($env{'request.course.id'}) { return ''; }
                   4643:     $coursedombuf{$env{'request.course.id'}}=
                   4644:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4645:     $coursenumbuf{$env{'request.course.id'}}=
                   4646:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4647:     $coursehombuf{$env{'request.course.id'}}=
                   4648:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4649:     $coursedescrbuf{$env{'request.course.id'}}=
                   4650:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4651:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4652:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4653:     $courseownerbuf{$env{'request.course.id'}}=
                   4654:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4655:     $coursetypebuf{$env{'request.course.id'}}=
                   4656:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4657:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4658: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4659:     } else {
1.620     albertel 4660: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4661:     }
1.620     albertel 4662:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4663: 	&flushcourselogs();
                   4664:     }
1.158     www      4665: }
                   4666: 
                   4667: sub courseacclog {
                   4668:     my $fnsymb=shift;
1.620     albertel 4669:     unless ($env{'request.course.id'}) { return ''; }
                   4670:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4671:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4672:         $what.=':POST';
1.583     matthew  4673:         # FIXME: Probably ought to escape things....
1.800     albertel 4674: 	foreach my $key (keys(%env)) {
                   4675:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4676:                 my $formitem = $1;
                   4677:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4678:                     $what.=':'.$formitem.'='.$env{$key};
                   4679:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4680:                     $what.=':'.$formitem.'='.$env{$key};
                   4681:                 }
1.158     www      4682:             }
1.191     harris41 4683:         }
1.583     matthew  4684:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4685:         # FIXME: We should not be depending on a form parameter that someone
                   4686:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4687:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4688:             $what.= ':POST';
                   4689:             # FIXME: Probably ought to escape things....
                   4690:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4691:                                  'crsdiscuss') {
1.620     albertel 4692:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4693:             }
                   4694:         }
1.158     www      4695:     }
                   4696:     &courselog($what);
1.149     www      4697: }
                   4698: 
1.185     www      4699: sub countacc {
                   4700:     my $url=&declutter(shift);
1.458     matthew  4701:     return if (! defined($url) || $url eq '');
1.620     albertel 4702:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4703: #
                   4704: # Mark that this url was used in this course
                   4705: #
1.620     albertel 4706:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4707: #
                   4708: # Increase the access count for this resource in this child process
                   4709: #
1.281     www      4710:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4711:     $accesshash{$key}++;
1.185     www      4712: }
1.349     www      4713: 
1.361     www      4714: sub linklog {
                   4715:     my ($from,$to)=@_;
                   4716:     $from=&declutter($from);
                   4717:     $to=&declutter($to);
                   4718:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4719:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4720: }
1.1160    www      4721: 
                   4722: sub statslog {
                   4723:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4724:     if ($users<2) { return; }
                   4725:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4726:             'course'       => $env{'request.course.id'},
                   4727:             'sections'     => '"all"',
                   4728:             'num_students' => $users,
                   4729:             'part'         => $part,
                   4730:             'symb'         => $symb,
                   4731:             'mean_tries'   => $av_attempts,
                   4732:             'deg_of_diff'  => $degdiff});
                   4733:     foreach my $key (keys(%dynstore)) {
                   4734:         $accesshash{$key}=$dynstore{$key};
                   4735:     }
                   4736: }
1.361     www      4737:   
1.349     www      4738: sub userrolelog {
                   4739:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4740:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4741:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4742:        $userrolehash
                   4743:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4744:                     =$tend.':'.$tstart;
1.662     raeburn  4745:     }
1.1169    droeschl 4746:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4747:        $userrolehash
                   4748:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4749:                     =$tend.':'.$tstart;
                   4750:     }
1.1172.2.90  raeburn  4751:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4752:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4753:        $domainrolehash
                   4754:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4755:                     = $tend.':'.$tstart;
                   4756:     }
1.351     www      4757: }
                   4758: 
1.957     raeburn  4759: sub courserolelog {
                   4760:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4761:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4762:         my $cdom = $1;
                   4763:         my $cnum = $2;
                   4764:         my $sec = $3;
                   4765:         my $namespace = 'rolelog';
                   4766:         my %storehash = (
                   4767:                            role    => $trole,
                   4768:                            start   => $tstart,
                   4769:                            end     => $tend,
                   4770:                            selfenroll => $selfenroll,
                   4771:                            context    => $context,
                   4772:                         );
                   4773:         if ($trole eq 'gr') {
                   4774:             $namespace = 'groupslog';
                   4775:             $storehash{'group'} = $sec;
                   4776:         } else {
                   4777:             $storehash{'section'} = $sec;
                   4778:         }
                   4779:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4780:                    $domain,$cnum,$cdom);
                   4781:         if (($trole ne 'st') || ($sec ne '')) {
                   4782:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4783:         }
                   4784:     }
                   4785:     return;
                   4786: }
                   4787: 
1.1172.2.9  raeburn  4788: sub domainrolelog {
                   4789:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4790:     if ($area =~ m{^/($match_domain)/$}) {
                   4791:         my $cdom = $1;
                   4792:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4793:         my $namespace = 'rolelog';
                   4794:         my %storehash = (
                   4795:                            role    => $trole,
                   4796:                            start   => $tstart,
                   4797:                            end     => $tend,
                   4798:                            context => $context,
                   4799:                         );
                   4800:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4801:                    $domain,$domconfiguser,$cdom);
                   4802:     }
                   4803:     return;
                   4804: 
                   4805: }
                   4806: 
                   4807: sub coauthorrolelog {
                   4808:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4809:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4810:         my $audom = $1;
                   4811:         my $auname = $2;
                   4812:         my $namespace = 'rolelog';
                   4813:         my %storehash = (
                   4814:                            role    => $trole,
                   4815:                            start   => $tstart,
                   4816:                            end     => $tend,
                   4817:                            context => $context,
                   4818:                         );
                   4819:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4820:                    $domain,$auname,$audom);
                   4821:     }
                   4822:     return;
                   4823: }
                   4824: 
1.351     www      4825: sub get_course_adv_roles {
1.948     raeburn  4826:     my ($cid,$codes) = @_;
1.620     albertel 4827:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4828:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4829:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4830:     my %nothide=();
1.800     albertel 4831:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4832:         if ($user !~ /:/) {
                   4833: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4834:         } else {
                   4835:             $nothide{$user}=1;
                   4836:         }
1.470     www      4837:     }
1.1172.2.23  raeburn  4838:     my @possdoms = ($coursehash{'domain'});
                   4839:     if ($coursehash{'checkforpriv'}) {
                   4840:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4841:     }
1.351     www      4842:     my %returnhash=();
                   4843:     my %dumphash=
                   4844:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4845:     my $now=time;
1.997     raeburn  4846:     my %privileged;
1.1000    raeburn  4847:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4848: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4849:         if (($tstart) && ($tstart<0)) { next; }
                   4850:         if (($tend) && ($tend<$now)) { next; }
                   4851:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4852:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4853: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4854:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4855:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4856: 	if ($role eq 'cr') { next; }
1.948     raeburn  4857:         if ($codes) {
                   4858:             if ($section) { $role .= ':'.$section; }
                   4859:             if ($returnhash{$role}) {
                   4860:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4861:             } else {
                   4862:                 $returnhash{$role}=$username.':'.$domain;
                   4863:             }
1.351     www      4864:         } else {
1.988     raeburn  4865:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4866:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4867:             if ($returnhash{$key}) {
                   4868: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4869:             } else {
                   4870:                 $returnhash{$key}=$username.':'.$domain;
                   4871:             }
1.351     www      4872:         }
1.948     raeburn  4873:     }
1.400     www      4874:     return %returnhash;
                   4875: }
                   4876: 
                   4877: sub get_my_roles {
1.937     raeburn  4878:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4879:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4880:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4881:     my (%dumphash,%nothide);
1.1086    raeburn  4882:     if ($context eq 'userroles') {
1.1166    raeburn  4883:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4884:     } else {
1.1172.2.23  raeburn  4885:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4886:         if ($hidepriv) {
                   4887:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4888:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4889:                 if ($user !~ /:/) {
                   4890:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4891:                 } else {
                   4892:                     $nothide{$user} = 1;
                   4893:                 }
                   4894:             }
                   4895:         }
1.858     raeburn  4896:     }
1.400     www      4897:     my %returnhash=();
                   4898:     my $now=time;
1.999     raeburn  4899:     my %privileged;
1.800     albertel 4900:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4901:         my ($role,$tend,$tstart);
                   4902:         if ($context eq 'userroles') {
1.1149    raeburn  4903:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4904: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4905:         } else {
                   4906:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4907:         }
1.400     www      4908:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4909:         my $status = 'active';
1.939     raeburn  4910:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4911:             $status = 'previous';
                   4912:         } 
                   4913:         if (($tstart) && ($now<$tstart)) {
                   4914:             $status = 'future';
                   4915:         }
                   4916:         if (ref($types) eq 'ARRAY') {
                   4917:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4918:                 next;
                   4919:             } 
                   4920:         } else {
                   4921:             if ($status ne 'active') {
                   4922:                 next;
                   4923:             }
                   4924:         }
1.867     raeburn  4925:         my ($rolecode,$username,$domain,$section,$area);
                   4926:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4927:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4928:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4929:         } else {
                   4930:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4931:         }
1.832     raeburn  4932:         if (ref($roledoms) eq 'ARRAY') {
                   4933:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4934:                 next;
                   4935:             }
                   4936:         }
                   4937:         if (ref($roles) eq 'ARRAY') {
                   4938:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4939:                 if ($role =~ /^cr\//) {
                   4940:                     if (!grep(/^cr$/,@{$roles})) {
                   4941:                         next;
                   4942:                     }
1.1104    raeburn  4943:                 } elsif ($role =~ /^gr\//) {
                   4944:                     if (!grep(/^gr$/,@{$roles})) {
                   4945:                         next;
                   4946:                     }
1.922     raeburn  4947:                 } else {
                   4948:                     next;
                   4949:                 }
1.832     raeburn  4950:             }
1.867     raeburn  4951:         }
1.937     raeburn  4952:         if ($hidepriv) {
1.1172.2.23  raeburn  4953:             my @privroles = ('dc','su');
1.999     raeburn  4954:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4955:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4956:             } else {
1.1172.2.23  raeburn  4957:                 my $possdoms = [$domain];
                   4958:                 if (ref($roledoms) eq 'ARRAY') {
                   4959:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4960:                 }
1.1172.2.23  raeburn  4961:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4962:                     if (!$nothide{$username.':'.$domain}) {
                   4963:                         next;
                   4964:                     }
                   4965:                 }
1.937     raeburn  4966:             }
                   4967:         }
1.933     raeburn  4968:         if ($withsec) {
                   4969:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4970:                 $tstart.':'.$tend;
                   4971:         } else {
                   4972:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4973:         }
1.832     raeburn  4974:     }
1.373     www      4975:     return %returnhash;
1.399     www      4976: }
                   4977: 
1.1172.2.89  raeburn  4978: sub get_all_adhocroles {
                   4979:     my ($dom) = @_;
                   4980:     my @roles_by_num = ();
                   4981:     my %domdefaults = &get_domain_defaults($dom);
                   4982:     my (%description,%access_in_dom,%access_info);
                   4983:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4984:         my $count = 0;
                   4985:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4986:         my %ordered;
                   4987:         foreach my $role (sort(keys(%domcurrent))) {
                   4988:             my ($order,$desc,$access_in_dom);
                   4989:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4990:                 $order = $domcurrent{$role}{'order'};
                   4991:                 $desc = $domcurrent{$role}{'desc'};
                   4992:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4993:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4994:             }
                   4995:             if ($order eq '') {
                   4996:                 $order = $count;
                   4997:             }
                   4998:             $ordered{$order} = $role;
                   4999:             if ($desc ne '') {
                   5000:                 $description{$role} = $desc;
                   5001:             } else {
                   5002:                 $description{$role}= $role;
                   5003:             }
                   5004:             $count++;
                   5005:         }
                   5006:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5007:             push(@roles_by_num,$ordered{$item});
                   5008:         }
                   5009:     }
                   5010:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5011: }
                   5012: 
                   5013: sub get_my_adhocroles {
                   5014:     my ($cid,$checkreg) = @_;
                   5015:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5016:     if ($env{'request.course.id'} eq $cid) {
                   5017:         $cdom = $env{'course.'.$cid.'.domain'};
                   5018:         $cnum = $env{'course.'.$cid.'.num'};
                   5019:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5020:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5021:         $cdom = $1;
                   5022:         $cnum = $2;
                   5023:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5024:                                      $cdom,$cnum);
                   5025:     }
                   5026:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5027:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5028:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5029:         if ($rosterhash{$user} ne '') {
                   5030:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5031:             return ([],{}) if ($type eq 'auto');
                   5032:         }
                   5033:     }
                   5034:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5035:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5036:             my $then=$env{'user.login.time'};
                   5037:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5038:             if (!$update) {
                   5039:                 $update = $then;
                   5040:             }
                   5041:             my @liveroles;
                   5042:             foreach my $role ('dh','da') {
                   5043:                 if ($env{"user.role.$role./$cdom/"}) {
                   5044:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5045:                     my $limit = $update;
                   5046:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5047:                         $limit = $then;
                   5048:                     }
                   5049:                     my $activerole = 1;
                   5050:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5051:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5052:                     if ($activerole) {
                   5053:                         push(@liveroles,$role);
                   5054:                     }
                   5055:                 }
                   5056:             }
                   5057:             if (@liveroles) {
1.1172.2.89  raeburn  5058:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5059:                     my ($accessref,$accessinfo,%access_in_dom);
                   5060:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5061:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5062:                         if (@{$roles_by_num}) {
                   5063:                             my %settings;
                   5064:                             if ($env{'request.course.id'} eq $cid) {
                   5065:                                 foreach my $envkey (keys(%env)) {
                   5066:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5067:                                         $settings{$1} = $env{$envkey};
                   5068:                                     }
                   5069:                                 }
                   5070:                             } else {
                   5071:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5072:                             }
                   5073:                             my %setincrs;
                   5074:                             if ($settings{'internal.adhocaccess'}) {
                   5075:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5076:                             }
                   5077:                             my @statuses;
                   5078:                             if ($env{'environment.inststatus'}) {
                   5079:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5080:                             }
                   5081:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5082:                             if (ref($accessref) eq 'HASH') {
                   5083:                                 %access_in_dom = %{$accessref};
                   5084:                             }
                   5085:                             foreach my $role (@{$roles_by_num}) {
                   5086:                                 my ($curraccess,@okstatus,@personnel);
                   5087:                                 if ($setincrs{$role}) {
                   5088:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5089:                                     if ($curraccess eq 'status') {
                   5090:                                         @okstatus = split(/\&/,$rest);
                   5091:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5092:                                         @personnel = split(/\&/,$rest);
                   5093:                                     }
                   5094:                                 } else {
                   5095:                                     $curraccess = $access_in_dom{$role};
                   5096:                                     if (ref($accessinfo) eq 'HASH') {
                   5097:                                         if ($curraccess eq 'status') {
                   5098:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5099:                                                 @okstatus = @{$accessinfo->{$role}};
                   5100:                                             }
                   5101:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5102:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5103:                                                 @personnel = @{$accessinfo->{$role}};
                   5104:                                             }
                   5105:                                         }
                   5106:                                     }
                   5107:                                 }
                   5108:                                 if ($curraccess eq 'none') {
                   5109:                                     next;
                   5110:                                 } elsif ($curraccess eq 'all') {
                   5111:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5112:                                 } elsif ($curraccess eq 'dh') {
                   5113:                                     if (grep(/^dh$/,@liveroles)) {
                   5114:                                         push(@possroles,$role);
                   5115:                                     } else {
                   5116:                                         next;
                   5117:                                     }
                   5118:                                 } elsif ($curraccess eq 'da') {
                   5119:                                     if (grep(/^da$/,@liveroles)) {
                   5120:                                         push(@possroles,$role);
                   5121:                                     } else {
                   5122:                                         next;
                   5123:                                     }
1.1172.2.89  raeburn  5124:                                 } elsif ($curraccess eq 'status') {
                   5125:                                     if (@okstatus) {
                   5126:                                         if (!@statuses) {
                   5127:                                             if (grep(/^default$/,@okstatus)) {
                   5128:                                                 push(@possroles,$role);
                   5129:                                             }
                   5130:                                         } else {
                   5131:                                             foreach my $status (@okstatus) {
                   5132:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5133:                                                     push(@possroles,$role);
                   5134:                                                     last;
                   5135:                                                 }
                   5136:                                             }
                   5137:                                         }
                   5138:                                     }
                   5139:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5140:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5141:                                         if ($curraccess eq 'exc') {
                   5142:                                             push(@possroles,$role);
                   5143:                                         }
                   5144:                                     } elsif ($curraccess eq 'inc') {
                   5145:                                         push(@possroles,$role);
                   5146:                                     }
                   5147:                                 }
                   5148:                             }
                   5149:                         }
                   5150:                     }
                   5151:                 }
                   5152:             }
                   5153:         }
                   5154:     }
                   5155:     unless (ref($description) eq 'HASH') {
                   5156:         if (ref($roles_by_num) eq 'ARRAY') {
                   5157:             my %desc;
                   5158:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5159:             $description = \%desc;
                   5160:         } else {
                   5161:             $description = {};
                   5162:         }
                   5163:     }
                   5164:     return (\@possroles,$description);
                   5165: }
                   5166: 
1.399     www      5167: # ----------------------------------------------------- Frontpage Announcements
                   5168: #
                   5169: #
                   5170: 
                   5171: sub postannounce {
                   5172:     my ($server,$text)=@_;
1.844     albertel 5173:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5174:     unless ($text=~/\w/) { $text=''; }
                   5175:     return &reply('setannounce:'.&escape($text),$server);
                   5176: }
                   5177: 
                   5178: sub getannounce {
1.448     albertel 5179: 
1.1172.2.96  raeburn  5180:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5181: 	my $announcement='';
1.800     albertel 5182: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5183: 	close($fh);
1.399     www      5184: 	if ($announcement=~/\w/) { 
                   5185: 	    return 
                   5186:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5187:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5188: 	} else {
                   5189: 	    return '';
                   5190: 	}
                   5191:     } else {
                   5192: 	return '';
                   5193:     }
1.351     www      5194: }
1.353     www      5195: 
                   5196: # ---------------------------------------------------------- Course ID routines
                   5197: # Deal with domain's nohist_courseid.db files
                   5198: #
                   5199: 
                   5200: sub courseidput {
1.921     raeburn  5201:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5202:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5203:     my $outcome;
                   5204:     if ($caller eq 'timeonly') {
                   5205:         my $cids = '';
                   5206:         foreach my $item (keys(%$storehash)) {
                   5207:             $cids.=&escape($item).'&';
                   5208:         }
                   5209:         $cids=~s/\&$//;
                   5210:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5211:                           $coursehome);       
                   5212:     } else {
                   5213:         my $items = '';
                   5214:         foreach my $item (keys(%$storehash)) {
                   5215:             $items.= &escape($item).'='.
                   5216:                      &freeze_escape($$storehash{$item}).'&';
                   5217:         }
                   5218:         $items=~s/\&$//;
                   5219:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5220:                           $coursehome);
1.918     raeburn  5221:     }
                   5222:     if ($outcome eq 'unknown_cmd') {
                   5223:         my $what;
                   5224:         foreach my $cid (keys(%$storehash)) {
                   5225:             $what .= &escape($cid).'=';
1.921     raeburn  5226:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5227:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5228:             }
                   5229:             $what =~ s/\:$/&/;
                   5230:         }
                   5231:         $what =~ s/\&$//;  
                   5232:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5233:     } else {
                   5234:         return $outcome;
                   5235:     }
1.353     www      5236: }
                   5237: 
                   5238: sub courseiddump {
1.921     raeburn  5239:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5240:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5241:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5242:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5243:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5244:     my $as_hash = 1;
                   5245:     my %returnhash;
                   5246:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5247:     my %libserv = &all_library();
                   5248:     foreach my $tryserver (keys(%libserv)) {
                   5249:         if ( (  $hostidflag == 1 
                   5250: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5251: 	     || (!defined($hostidflag)) ) {
                   5252: 
1.918     raeburn  5253: 	    if (($domfilter eq '') ||
                   5254: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5255:                 my $rep;
                   5256:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5257:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5258:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5259:                                 &escape($descfilter), &escape($instcodefilter),
                   5260:                                 &escape($ownerfilter), &escape($coursefilter),
                   5261:                                 &escape($typefilter), &escape($regexp_ok),
                   5262:                                 $as_hash, &escape($selfenrollonly),
                   5263:                                 &escape($catfilter), $showhidden, $caller,
                   5264:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5265:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5266:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5267:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5268:                 } else {
                   5269:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5270:                              $sincefilter.':'.&escape($descfilter).':'.
                   5271:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5272:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5273:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5274:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5275:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5276:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5277:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5278:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5279:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5280:                 }
                   5281: 
1.918     raeburn  5282:                 my @pairs=split(/\&/,$rep);
                   5283:                 foreach my $item (@pairs) {
                   5284:                     my ($key,$value)=split(/\=/,$item,2);
                   5285:                     $key = &unescape($key);
                   5286:                     next if ($key =~ /^error: 2 /);
                   5287:                     my $result = &thaw_unescape($value);
                   5288:                     if (ref($result) eq 'HASH') {
                   5289:                         $returnhash{$key}=$result;
                   5290:                     } else {
1.921     raeburn  5291:                         my @responses = split(/:/,$value);
                   5292:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5293:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5294:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5295:                         }
1.1008    raeburn  5296:                     }
1.353     www      5297:                 }
                   5298:             }
                   5299:         }
                   5300:     }
                   5301:     return %returnhash;
                   5302: }
                   5303: 
1.1055    raeburn  5304: sub courselastaccess {
                   5305:     my ($cdom,$cnum,$hostidref) = @_;
                   5306:     my %returnhash;
                   5307:     if ($cdom && $cnum) {
                   5308:         my $chome = &homeserver($cnum,$cdom);
                   5309:         if ($chome ne 'no_host') {
                   5310:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5311:             &extract_lastaccess(\%returnhash,$rep);
                   5312:         }
                   5313:     } else {
                   5314:         if (!$cdom) { $cdom=''; }
                   5315:         my %libserv = &all_library();
                   5316:         foreach my $tryserver (keys(%libserv)) {
                   5317:             if (ref($hostidref) eq 'ARRAY') {
                   5318:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5319:             } 
                   5320:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5321:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5322:                 &extract_lastaccess(\%returnhash,$rep);
                   5323:             }
                   5324:         }
                   5325:     }
                   5326:     return %returnhash;
                   5327: }
                   5328: 
                   5329: sub extract_lastaccess {
                   5330:     my ($returnhash,$rep) = @_;
                   5331:     if (ref($returnhash) eq 'HASH') {
                   5332:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5333:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5334:                  $rep eq '') {
                   5335:             my @pairs=split(/\&/,$rep);
                   5336:             foreach my $item (@pairs) {
                   5337:                 my ($key,$value)=split(/\=/,$item,2);
                   5338:                 $key = &unescape($key);
                   5339:                 next if ($key =~ /^error: 2 /);
                   5340:                 $returnhash->{$key} = &thaw_unescape($value);
                   5341:             }
                   5342:         }
                   5343:     }
                   5344:     return;
                   5345: }
                   5346: 
1.658     raeburn  5347: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5348: 
                   5349: sub dcmailput {
1.685     raeburn  5350:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5351:     my $status = &Apache::lonnet::critical(
1.740     www      5352:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5353:        &escape($message),$server);
1.662     raeburn  5354:     return $status;
                   5355: }
                   5356: 
1.658     raeburn  5357: sub dcmaildump {
                   5358:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5359:     my %returnhash=();
1.846     albertel 5360: 
                   5361:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5362:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5363:                                                          &escape($enddate).':';
                   5364: 	my @esc_senders=map { &escape($_)} @$senders;
                   5365: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5366: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5367:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5368:             if (($key) && ($value)) {
                   5369:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5370:             }
                   5371:         }
                   5372:     }
                   5373:     return %returnhash;
                   5374: }
1.662     raeburn  5375: # ---------------------------------------------------------- Domain roles
                   5376: 
                   5377: sub get_domain_roles {
                   5378:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5379:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5380:         $startdate = '.';
                   5381:     }
1.1018    raeburn  5382:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5383:         $enddate = '.';
                   5384:     }
1.922     raeburn  5385:     my $rolelist;
                   5386:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5387:         $rolelist = join('&',@{$roles});
1.922     raeburn  5388:     }
1.662     raeburn  5389:     my %personnel = ();
1.841     albertel 5390: 
                   5391:     my %servers = &get_servers($dom,'library');
                   5392:     foreach my $tryserver (keys(%servers)) {
                   5393: 	%{$personnel{$tryserver}}=();
                   5394: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5395: 					    &escape($startdate).':'.
                   5396: 					    &escape($enddate).':'.
                   5397: 					    &escape($rolelist), $tryserver))) {
                   5398: 	    my ($key,$value) = split(/\=/,$line,2);
                   5399: 	    if (($key) && ($value)) {
                   5400: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5401: 	    }
                   5402: 	}
1.662     raeburn  5403:     }
                   5404:     return %personnel;
                   5405: }
1.658     raeburn  5406: 
1.1172.2.89  raeburn  5407: sub get_active_domroles {
                   5408:     my ($dom,$roles) = @_;
                   5409:     return () unless (ref($roles) eq 'ARRAY');
                   5410:     my $now = time;
                   5411:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5412:     my %domroles;
                   5413:     foreach my $server (keys(%dompersonnel)) {
                   5414:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5415:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5416:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5417:         }
                   5418:     }
                   5419:     return %domroles;
                   5420: }
                   5421: 
1.1057    www      5422: # ----------------------------------------------------------- Interval timing 
1.149     www      5423: 
1.1153    www      5424: {
                   5425: # Caches needed for speedup of navmaps
                   5426: # We don't want to cache this for very long at all (5 seconds at most)
                   5427: # 
                   5428: # The user for whom we cache
                   5429: my $cachedkey='';
                   5430: # The cached times for this user
                   5431: my %cachedtimes=();
                   5432: # When this was last done
1.1172.2.66  raeburn  5433: my $cachedtime='';
1.1153    www      5434: 
                   5435: sub load_all_first_access {
1.1154    raeburn  5436:     my ($uname,$udom)=@_;
1.1156    www      5437:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5438:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5439:         return;
                   5440:     }
                   5441:     $cachedtime=time;
                   5442:     $cachedkey=$uname.':'.$udom;
                   5443:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5444: }
                   5445: 
1.504     albertel 5446: sub get_first_access {
1.1162    raeburn  5447:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5448:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5449:     if ($argsymb) { $symb=$argsymb; }
                   5450:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5451:     if ($argmap) { $map = $argmap; }
1.926     albertel 5452:     if ($type eq 'course') {
                   5453: 	$res='course';
                   5454:     } elsif ($type eq 'map') {
1.588     albertel 5455: 	$res=&symbread($map);
                   5456:     } else {
                   5457: 	$res=$symb;
                   5458:     }
1.1153    www      5459:     &load_all_first_access($uname,$udom);
                   5460:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5461: }
                   5462: 
                   5463: sub set_first_access {
1.1162    raeburn  5464:     my ($type,$interval)=@_;
1.790     albertel 5465:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5466:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5467:     if ($type eq 'course') {
                   5468: 	$res='course';
                   5469:     } elsif ($type eq 'map') {
1.588     albertel 5470: 	$res=&symbread($map);
                   5471:     } else {
                   5472: 	$res=$symb;
                   5473:     }
1.1153    www      5474:     $cachedkey='';
1.1162    raeburn  5475:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5476:     if ($firstaccess) {
                   5477:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5478:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5479:                  "in $courseid");
                   5480:         return 'already_set';
                   5481:     } else {
1.1162    raeburn  5482:         my $start = time;
                   5483: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5484:                           $udom,$uname);
                   5485:         if ($putres eq 'ok') {
                   5486:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5487:                  $udom,$uname); 
                   5488:             &appenv(
                   5489:                      {
                   5490:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5491:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5492:                      }
                   5493:                   );
1.1172.2.97  raeburn  5494:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5495:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5496:             }
1.1172.2.102  raeburn  5497:         } elsif ($putres ne 'refused') {
                   5498:             &logthis("Result: $putres when attempting to set first access time ".
                   5499:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5500:         }
                   5501:         return $putres;
1.505     albertel 5502:     }
                   5503:     return 'already_set';
1.504     albertel 5504: }
1.1153    www      5505: }
1.1172.2.32  raeburn  5506: 
                   5507: sub checkout {
                   5508:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5509:     my $now=time;
                   5510:     my $lonhost=$perlvar{'lonHostID'};
                   5511:     my $infostr=&escape(
                   5512:                  'CHECKOUTTOKEN&'.
                   5513:                  $tuname.'&'.
                   5514:                  $tudom.'&'.
                   5515:                  $tcrsid.'&'.
                   5516:                  $symb.'&'.
                   5517:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5518:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5519:     if ($token=~/^error\:/) {
                   5520:         &logthis("<font color=\"blue\">WARNING: ".
                   5521:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5522:                  "</font>");
                   5523:         return '';
                   5524:     }
                   5525: 
                   5526:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5527:     $token=~tr/a-z/A-Z/;
                   5528: 
                   5529:     my %infohash=('resource.0.outtoken' => $token,
                   5530:                   'resource.0.checkouttime' => $now,
                   5531:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5532: 
                   5533:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5534:        return '';
                   5535:     } else {
                   5536:         &logthis("<font color=\"blue\">WARNING: ".
                   5537:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5538:                  "</font>");
                   5539:     }
                   5540: 
                   5541:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5542:                          &escape('Checkout '.$infostr.' - '.
                   5543:                                                  $token)) ne 'ok') {
                   5544:         return '';
                   5545:     } else {
                   5546:         &logthis("<font color=\"blue\">WARNING: ".
                   5547:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5548:                  "</font>");
                   5549:     }
                   5550:     return $token;
                   5551: }
                   5552: 
                   5553: # ------------------------------------------------------------ Check in an item
                   5554: 
                   5555: sub checkin {
                   5556:     my $token=shift;
                   5557:     my $now=time;
                   5558:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5559:     $lonhost=~tr/A-Z/a-z/;
                   5560:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5561:     $dtoken=~s/\W/\_/g;
                   5562:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5563:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5564: 
                   5565:     unless (($tuname) && ($tudom)) {
                   5566:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5567:         return '';
                   5568:     }
                   5569: 
                   5570:     unless (&allowed('mgr',$tcrsid)) {
                   5571:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5572:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5573:         return '';
                   5574:     }
                   5575: 
                   5576:     my %infohash=('resource.0.intoken' => $token,
                   5577:                   'resource.0.checkintime' => $now,
                   5578:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5579: 
                   5580:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5581:        return '';
                   5582:     }
                   5583: 
                   5584:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5585:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5586:         return '';
                   5587:     }
                   5588: 
                   5589:     return ($symb,$tuname,$tudom,$tcrsid);
                   5590: }
                   5591: 
1.110     www      5592: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5593: 
                   5594: sub expirespread {
                   5595:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5596:     my $cid=$env{'request.course.id'}; 
1.110     www      5597:     if ($cid) {
                   5598:        my $now=time;
                   5599:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5600:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5601:                             $env{'course.'.$cid.'.num'}.
1.110     www      5602: 	        	    ':nohist_expirationdates:'.
                   5603:                             &escape($key).'='.$now,
1.620     albertel 5604:                             $env{'course.'.$cid.'.home'})
1.110     www      5605:     }
                   5606:     return 'ok';
1.14      www      5607: }
                   5608: 
1.109     www      5609: # ----------------------------------------------------- Devalidate Spreadsheets
                   5610: 
                   5611: sub devalidate {
1.325     www      5612:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5613:     my $cid=$env{'request.course.id'}; 
1.109     www      5614:     if ($cid) {
1.391     matthew  5615:         # delete the stored spreadsheets for
                   5616:         # - the student level sheet of this user in course's homespace
                   5617:         # - the assessment level sheet for this resource 
                   5618:         #   for this user in user's homespace
1.553     albertel 5619: 	# - current conditional state info
1.325     www      5620: 	my $key=$uname.':'.$udom.':';
1.109     www      5621:         my $status=
1.299     matthew  5622: 	    &del('nohist_calculatedsheets',
1.391     matthew  5623: 		 [$key.'studentcalc:'],
1.620     albertel 5624: 		 $env{'course.'.$cid.'.domain'},
                   5625: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5626: 		.' '.
                   5627: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5628: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5629:         unless ($status eq 'ok ok') {
                   5630:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5631:                     $uname.' at '.$udom.' for '.
1.109     www      5632: 		    $symb.': '.$status);
1.133     albertel 5633:         }
1.553     albertel 5634: 	&delenv('user.state.'.$cid);
1.109     www      5635:     }
                   5636: }
                   5637: 
1.265     albertel 5638: sub get_scalar {
                   5639:     my ($string,$end) = @_;
                   5640:     my $value;
                   5641:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5642: 	$value = $1;
                   5643:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5644: 	$value = $1;
                   5645:     }
                   5646:     return &unescape($value);
                   5647: }
                   5648: 
                   5649: sub array2str {
                   5650:   my (@array) = @_;
                   5651:   my $result=&arrayref2str(\@array);
                   5652:   $result=~s/^__ARRAY_REF__//;
                   5653:   $result=~s/__END_ARRAY_REF__$//;
                   5654:   return $result;
                   5655: }
                   5656: 
1.204     albertel 5657: sub arrayref2str {
                   5658:   my ($arrayref) = @_;
1.265     albertel 5659:   my $result='__ARRAY_REF__';
1.204     albertel 5660:   foreach my $elem (@$arrayref) {
1.265     albertel 5661:     if(ref($elem) eq 'ARRAY') {
                   5662:       $result.=&arrayref2str($elem).'&';
                   5663:     } elsif(ref($elem) eq 'HASH') {
                   5664:       $result.=&hashref2str($elem).'&';
                   5665:     } elsif(ref($elem)) {
                   5666:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5667:     } else {
                   5668:       $result.=&escape($elem).'&';
                   5669:     }
                   5670:   }
                   5671:   $result=~s/\&$//;
1.265     albertel 5672:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5673:   return $result;
                   5674: }
                   5675: 
1.168     albertel 5676: sub hash2str {
1.204     albertel 5677:   my (%hash) = @_;
                   5678:   my $result=&hashref2str(\%hash);
1.265     albertel 5679:   $result=~s/^__HASH_REF__//;
                   5680:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5681:   return $result;
                   5682: }
                   5683: 
                   5684: sub hashref2str {
                   5685:   my ($hashref)=@_;
1.265     albertel 5686:   my $result='__HASH_REF__';
1.800     albertel 5687:   foreach my $key (sort(keys(%$hashref))) {
                   5688:     if (ref($key) eq 'ARRAY') {
                   5689:       $result.=&arrayref2str($key).'=';
                   5690:     } elsif (ref($key) eq 'HASH') {
                   5691:       $result.=&hashref2str($key).'=';
                   5692:     } elsif (ref($key)) {
1.265     albertel 5693:       $result.='=';
1.800     albertel 5694:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5695:     } else {
1.1132    raeburn  5696: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5697:     }
                   5698: 
1.800     albertel 5699:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5700:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5701:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5702:       $result.=&hashref2str($hashref->{$key}).'&';
                   5703:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5704:        $result.='&';
1.800     albertel 5705:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5706:     } else {
1.800     albertel 5707:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5708:     }
                   5709:   }
1.168     albertel 5710:   $result=~s/\&$//;
1.265     albertel 5711:   $result .= '__END_HASH_REF__';
1.168     albertel 5712:   return $result;
                   5713: }
                   5714: 
                   5715: sub str2hash {
1.265     albertel 5716:     my ($string)=@_;
                   5717:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5718:     return %$hash;
                   5719: }
                   5720: 
                   5721: sub str2hashref {
1.168     albertel 5722:   my ($string) = @_;
1.265     albertel 5723: 
                   5724:   my %hash;
                   5725: 
                   5726:   if($string !~ /^__HASH_REF__/) {
                   5727:       if (! ($string eq '' || !defined($string))) {
                   5728: 	  $hash{'error'}='Not hash reference';
                   5729:       }
                   5730:       return (\%hash, $string);
                   5731:   }
                   5732: 
                   5733:   $string =~ s/^__HASH_REF__//;
                   5734: 
                   5735:   while($string !~ /^__END_HASH_REF__/) {
                   5736:       #key
                   5737:       my $key='';
                   5738:       if($string =~ /^__HASH_REF__/) {
                   5739:           ($key, $string)=&str2hashref($string);
                   5740:           if(defined($key->{'error'})) {
                   5741:               $hash{'error'}='Bad data';
                   5742:               return (\%hash, $string);
                   5743:           }
                   5744:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5745:           ($key, $string)=&str2arrayref($string);
                   5746:           if($key->[0] eq 'Array reference error') {
                   5747:               $hash{'error'}='Bad data';
                   5748:               return (\%hash, $string);
                   5749:           }
                   5750:       } else {
                   5751:           $string =~ s/^(.*?)=//;
1.267     albertel 5752: 	  $key=&unescape($1);
1.265     albertel 5753:       }
                   5754:       $string =~ s/^=//;
                   5755: 
                   5756:       #value
                   5757:       my $value='';
                   5758:       if($string =~ /^__HASH_REF__/) {
                   5759:           ($value, $string)=&str2hashref($string);
                   5760:           if(defined($value->{'error'})) {
                   5761:               $hash{'error'}='Bad data';
                   5762:               return (\%hash, $string);
                   5763:           }
                   5764:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5765:           ($value, $string)=&str2arrayref($string);
                   5766:           if($value->[0] eq 'Array reference error') {
                   5767:               $hash{'error'}='Bad data';
                   5768:               return (\%hash, $string);
                   5769:           }
                   5770:       } else {
                   5771: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5772:       }
                   5773:       $string =~ s/^&//;
                   5774: 
                   5775:       $hash{$key}=$value;
1.204     albertel 5776:   }
1.265     albertel 5777: 
                   5778:   $string =~ s/^__END_HASH_REF__//;
                   5779: 
                   5780:   return (\%hash, $string);
1.204     albertel 5781: }
                   5782: 
                   5783: sub str2array {
1.265     albertel 5784:     my ($string)=@_;
                   5785:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5786:     return @$array;
                   5787: }
                   5788: 
                   5789: sub str2arrayref {
1.204     albertel 5790:   my ($string) = @_;
1.265     albertel 5791:   my @array;
                   5792: 
                   5793:   if($string !~ /^__ARRAY_REF__/) {
                   5794:       if (! ($string eq '' || !defined($string))) {
                   5795: 	  $array[0]='Array reference error';
                   5796:       }
                   5797:       return (\@array, $string);
                   5798:   }
                   5799: 
                   5800:   $string =~ s/^__ARRAY_REF__//;
                   5801: 
                   5802:   while($string !~ /^__END_ARRAY_REF__/) {
                   5803:       my $value='';
                   5804:       if($string =~ /^__HASH_REF__/) {
                   5805:           ($value, $string)=&str2hashref($string);
                   5806:           if(defined($value->{'error'})) {
                   5807:               $array[0] ='Array reference error';
                   5808:               return (\@array, $string);
                   5809:           }
                   5810:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5811:           ($value, $string)=&str2arrayref($string);
                   5812:           if($value->[0] eq 'Array reference error') {
                   5813:               $array[0] ='Array reference error';
                   5814:               return (\@array, $string);
                   5815:           }
                   5816:       } else {
                   5817: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5818:       }
                   5819:       $string =~ s/^&//;
                   5820: 
                   5821:       push(@array, $value);
1.191     harris41 5822:   }
1.265     albertel 5823: 
                   5824:   $string =~ s/^__END_ARRAY_REF__//;
                   5825: 
                   5826:   return (\@array, $string);
1.168     albertel 5827: }
                   5828: 
1.167     albertel 5829: # -------------------------------------------------------------------Temp Store
                   5830: 
1.168     albertel 5831: sub tmpreset {
                   5832:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5833:   if (!$symb) {
                   5834:     $symb=&symbread();
1.620     albertel 5835:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5836:   }
                   5837:   $symb=escape($symb);
                   5838: 
1.620     albertel 5839:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5840:   $namespace=~s/\//\_/g;
                   5841:   $namespace=~s/\W//g;
                   5842: 
1.620     albertel 5843:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5844:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5845:   if ($domain eq 'public' && $stuname eq 'public') {
                   5846:       $stuname=$ENV{'REMOTE_ADDR'};
                   5847:   }
1.1117    foxr     5848:   my $path=LONCAPA::tempdir();
1.168     albertel 5849:   my %hash;
                   5850:   if (tie(%hash,'GDBM_File',
                   5851: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5852: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5853:     foreach my $key (keys(%hash)) {
1.180     albertel 5854:       if ($key=~ /:$symb/) {
1.168     albertel 5855: 	delete($hash{$key});
                   5856:       }
                   5857:     }
                   5858:   }
                   5859: }
                   5860: 
1.167     albertel 5861: sub tmpstore {
1.168     albertel 5862:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5863: 
                   5864:   if (!$symb) {
                   5865:     $symb=&symbread();
1.620     albertel 5866:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5867:   }
                   5868:   $symb=escape($symb);
                   5869: 
                   5870:   if (!$namespace) {
                   5871:     # I don't think we would ever want to store this for a course.
                   5872:     # it seems this will only be used if we don't have a course.
1.620     albertel 5873:     #$namespace=$env{'request.course.id'};
1.168     albertel 5874:     #if (!$namespace) {
1.620     albertel 5875:       $namespace=$env{'request.state'};
1.168     albertel 5876:     #}
                   5877:   }
                   5878:   $namespace=~s/\//\_/g;
                   5879:   $namespace=~s/\W//g;
1.620     albertel 5880:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5881:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5882:   if ($domain eq 'public' && $stuname eq 'public') {
                   5883:       $stuname=$ENV{'REMOTE_ADDR'};
                   5884:   }
1.168     albertel 5885:   my $now=time;
                   5886:   my %hash;
1.1117    foxr     5887:   my $path=LONCAPA::tempdir();
1.168     albertel 5888:   if (tie(%hash,'GDBM_File',
                   5889: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5890: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5891:     $hash{"version:$symb"}++;
                   5892:     my $version=$hash{"version:$symb"};
                   5893:     my $allkeys=''; 
                   5894:     foreach my $key (keys(%$storehash)) {
                   5895:       $allkeys.=$key.':';
1.591     albertel 5896:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5897:     }
                   5898:     $hash{"$version:$symb:timestamp"}=$now;
                   5899:     $allkeys.='timestamp';
                   5900:     $hash{"$version:keys:$symb"}=$allkeys;
                   5901:     if (untie(%hash)) {
                   5902:       return 'ok';
                   5903:     } else {
                   5904:       return "error:$!";
                   5905:     }
                   5906:   } else {
                   5907:     return "error:$!";
                   5908:   }
                   5909: }
1.167     albertel 5910: 
1.168     albertel 5911: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5912: 
1.168     albertel 5913: sub tmprestore {
                   5914:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5915: 
1.168     albertel 5916:   if (!$symb) {
                   5917:     $symb=&symbread();
1.620     albertel 5918:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5919:   }
                   5920:   $symb=escape($symb);
                   5921: 
1.620     albertel 5922:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5923: 
1.620     albertel 5924:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5925:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5926:   if ($domain eq 'public' && $stuname eq 'public') {
                   5927:       $stuname=$ENV{'REMOTE_ADDR'};
                   5928:   }
1.168     albertel 5929:   my %returnhash;
                   5930:   $namespace=~s/\//\_/g;
                   5931:   $namespace=~s/\W//g;
                   5932:   my %hash;
1.1117    foxr     5933:   my $path=LONCAPA::tempdir();
1.168     albertel 5934:   if (tie(%hash,'GDBM_File',
                   5935: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5936: 	  &GDBM_READER(),0640)) {
1.168     albertel 5937:     my $version=$hash{"version:$symb"};
                   5938:     $returnhash{'version'}=$version;
                   5939:     my $scope;
                   5940:     for ($scope=1;$scope<=$version;$scope++) {
                   5941:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5942:       my @keys=split(/:/,$vkeys);
                   5943:       my $key;
                   5944:       $returnhash{"$scope:keys"}=$vkeys;
                   5945:       foreach $key (@keys) {
1.591     albertel 5946: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5947: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5948:       }
                   5949:     }
1.168     albertel 5950:     if (!(untie(%hash))) {
                   5951:       return "error:$!";
                   5952:     }
                   5953:   } else {
                   5954:     return "error:$!";
                   5955:   }
                   5956:   return %returnhash;
1.167     albertel 5957: }
                   5958: 
1.9       www      5959: # ----------------------------------------------------------------------- Store
                   5960: 
                   5961: sub store {
1.1172.2.64  raeburn  5962:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5963:     my $home='';
                   5964: 
1.168     albertel 5965:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5966: 
1.213     www      5967:     $symb=&symbclean($symb);
1.122     albertel 5968:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5969: 
1.620     albertel 5970:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5971:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5972: 
                   5973:     &devalidate($symb,$stuname,$domain);
1.109     www      5974: 
                   5975:     $symb=escape($symb);
1.187     www      5976:     if (!$namespace) { 
1.620     albertel 5977:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5978:           return ''; 
                   5979:        } 
                   5980:     }
1.620     albertel 5981:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5982: 
                   5983:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5984:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5985: 
1.12      www      5986:     my $namevalue='';
1.800     albertel 5987:     foreach my $key (keys(%$storehash)) {
                   5988:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5989:     }
1.12      www      5990:     $namevalue=~s/\&$//;
1.187     www      5991:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5992:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5993: }
                   5994: 
1.47      www      5995: # -------------------------------------------------------------- Critical Store
                   5996: 
                   5997: sub cstore {
1.1172.2.64  raeburn  5998:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5999:     my $home='';
                   6000: 
1.168     albertel 6001:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6002: 
1.213     www      6003:     $symb=&symbclean($symb);
1.122     albertel 6004:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6005: 
1.620     albertel 6006:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6007:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6008: 
                   6009:     &devalidate($symb,$stuname,$domain);
1.109     www      6010: 
                   6011:     $symb=escape($symb);
1.187     www      6012:     if (!$namespace) { 
1.620     albertel 6013:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6014:           return ''; 
                   6015:        } 
                   6016:     }
1.620     albertel 6017:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6018: 
                   6019:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6020:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6021: 
1.47      www      6022:     my $namevalue='';
1.800     albertel 6023:     foreach my $key (keys(%$storehash)) {
                   6024:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6025:     }
1.47      www      6026:     $namevalue=~s/\&$//;
1.187     www      6027:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6028:     return critical
1.1172.2.64  raeburn  6029:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6030: }
                   6031: 
1.9       www      6032: # --------------------------------------------------------------------- Restore
                   6033: 
                   6034: sub restore {
1.124     www      6035:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6036:     my $home='';
                   6037: 
1.168     albertel 6038:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6039: 
1.122     albertel 6040:     if (!$symb) {
1.1172.2.26  raeburn  6041:         return if ($namespace eq 'courserequests');
                   6042:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6043:     } else {
1.1172.2.26  raeburn  6044:         unless ($namespace eq 'courserequests') {
                   6045:             $symb=&escape(&symbclean($symb));
                   6046:         }
1.122     albertel 6047:     }
1.188     www      6048:     if (!$namespace) { 
1.620     albertel 6049:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6050:           return ''; 
                   6051:        } 
                   6052:     }
1.620     albertel 6053:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6054:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6055:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6056:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6057: 
1.12      www      6058:     my %returnhash=();
1.800     albertel 6059:     foreach my $line (split(/\&/,$answer)) {
                   6060: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6061:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6062:     }
1.75      www      6063:     my $version;
                   6064:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6065:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6066:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6067:        }
1.75      www      6068:     }
1.13      www      6069:     return %returnhash;
1.34      www      6070: }
                   6071: 
                   6072: # ---------------------------------------------------------- Course Description
1.1118    foxr     6073: #
                   6074: #  
1.34      www      6075: 
                   6076: sub coursedescription {
1.731     albertel 6077:     my ($courseid,$args)=@_;
1.34      www      6078:     $courseid=~s/^\///;
1.49      www      6079:     $courseid=~s/\_/\//g;
1.34      www      6080:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6081:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6082:     my $normalid=$cdomain.'_'.$cnum;
                   6083:     # need to always cache even if we get errors otherwise we keep 
                   6084:     # trying and trying and trying to get the course description.
                   6085:     my %envhash=();
                   6086:     my %returnhash=();
1.731     albertel 6087:     
                   6088:     my $expiretime=600;
                   6089:     if ($env{'request.course.id'} eq $normalid) {
                   6090: 	$expiretime=120;
                   6091:     }
                   6092: 
                   6093:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6094:     if (!$args->{'freshen_cache'}
                   6095: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6096: 	foreach my $key (keys(%env)) {
                   6097: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6098: 	    my ($setting) = $1;
                   6099: 	    $returnhash{$setting} = $env{$key};
                   6100: 	}
                   6101: 	return %returnhash;
                   6102:     }
                   6103: 
1.1118    foxr     6104:     # get the data again
                   6105: 
1.731     albertel 6106:     if (!$args->{'one_time'}) {
                   6107: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6108:     }
1.811     albertel 6109: 
1.34      www      6110:     if ($chome ne 'no_host') {
1.302     albertel 6111:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6112:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6113: 	   my $username = $env{'user.name'}; # Defult username
                   6114: 	   if(defined $args->{'user'}) {
                   6115: 	       $username = $args->{'user'};
                   6116: 	   }
1.129     albertel 6117:            $returnhash{'home'}= $chome;
                   6118: 	   $returnhash{'domain'} = $cdomain;
                   6119: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6120:            if (!defined($returnhash{'type'})) {
                   6121:                $returnhash{'type'} = 'Course';
                   6122:            }
1.130     albertel 6123:            while (my ($name,$value) = each %returnhash) {
1.53      www      6124:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6125:            }
1.270     www      6126:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6127:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6128: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6129:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6130:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6131:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6132:        }
                   6133:     }
1.731     albertel 6134:     if (!$args->{'one_time'}) {
1.949     raeburn  6135: 	&appenv(\%envhash);
1.731     albertel 6136:     }
1.302     albertel 6137:     return %returnhash;
1.461     www      6138: }
                   6139: 
1.1080    raeburn  6140: sub update_released_required {
                   6141:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6142:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6143:         $cid = $env{'request.course.id'};
                   6144:         $cdom = $env{'course.'.$cid.'.domain'};
                   6145:         $cnum = $env{'course.'.$cid.'.num'};
                   6146:         $chome = $env{'course.'.$cid.'.home'};
                   6147:     }
                   6148:     if ($needsrelease) {
                   6149:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6150:         my $needsupdate;
                   6151:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6152:             $needsupdate = 1;
                   6153:         } else {
                   6154:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6155:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6156:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6157:                 $needsupdate = 1;
                   6158:             }
                   6159:         }
                   6160:         if ($needsupdate) {
                   6161:             my %needshash = (
                   6162:                              'internal.releaserequired' => $needsrelease,
                   6163:                             );
                   6164:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6165:             if ($putresult eq 'ok') {
                   6166:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6167:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6168:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6169:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6170:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6171:                 }
                   6172:             }
                   6173:         }
                   6174:     }
                   6175:     return;
                   6176: }
                   6177: 
1.461     www      6178: # -------------------------------------------------See if a user is privileged
                   6179: 
                   6180: sub privileged {
1.1172.2.23  raeburn  6181:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6182:     my $now = time;
1.1172.2.23  raeburn  6183:     my $roles;
                   6184:     if (ref($possroles) eq 'ARRAY') {
                   6185:         $roles = $possroles;
                   6186:     } else {
                   6187:         $roles = ['dc','su'];
                   6188:     }
                   6189:     if (ref($possdomains) eq 'ARRAY') {
                   6190:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6191:         foreach my $dom (@{$possdomains}) {
                   6192:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6193:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6194:                 foreach my $role (@{$roles}) {
                   6195:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6196:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6197:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6198:                             return 1 unless (($end && $end < $now) ||
                   6199:                                              ($start && $start > $now));
                   6200:                         }
                   6201:                     }
                   6202:                 }
                   6203:             }
                   6204:         }
                   6205:     } else {
                   6206:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6207:         my $now = time;
1.1170    droeschl 6208: 
1.1172.2.58  raeburn  6209:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6210:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6211:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6212:                 return 1 unless ($tend && $tend < $now)
                   6213:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6214:             }
1.1172.2.23  raeburn  6215:         }
                   6216:     }
1.461     www      6217:     return 0;
1.9       www      6218: }
1.1       albertel 6219: 
1.1172.2.23  raeburn  6220: sub privileged_by_domain {
                   6221:     my ($domains,$roles) = @_;
                   6222:     my %privileged = ();
                   6223:     my $cachetime = 60*60*24;
                   6224:     my $now = time;
                   6225:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6226:         return %privileged;
                   6227:     }
                   6228:     foreach my $dom (@{$domains}) {
                   6229:         next if (ref($privileged{$dom}) eq 'HASH');
                   6230:         my $needroles;
                   6231:         foreach my $role (@{$roles}) {
                   6232:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6233:             if (defined($cached)) {
                   6234:                 if (ref($result) eq 'HASH') {
                   6235:                     $privileged{$dom}{$role} = $result;
                   6236:                 }
                   6237:             } else {
                   6238:                 $needroles = 1;
                   6239:             }
                   6240:         }
                   6241:         if ($needroles) {
                   6242:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6243:             $privileged{$dom} = {};
                   6244:             foreach my $server (keys(%dompersonnel)) {
                   6245:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6246:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6247:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6248:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6249:                         next if ($end && $end < $now);
                   6250:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6251:                             $dompersonnel{$server}{$item};
                   6252:                     }
                   6253:                 }
                   6254:             }
                   6255:             if (ref($privileged{$dom}) eq 'HASH') {
                   6256:                 foreach my $role (@{$roles}) {
                   6257:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6258:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6259:                     } else {
                   6260:                         my %hash = ();
                   6261:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6262:                     }
                   6263:                 }
                   6264:             }
                   6265:         }
                   6266:     }
                   6267:     return %privileged;
                   6268: }
                   6269: 
1.103     harris41 6270: # -------------------------------------------------------- Get user privileges
1.11      www      6271: 
                   6272: sub rolesinit {
1.1169    droeschl 6273:     my ($domain, $username) = @_;
                   6274:     my %userroles = ('user.login.time' => time);
                   6275:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6276: 
                   6277:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6278:     # also, blocking can be triggered by an activating timer
                   6279:     # it's saved in the user's %env.
                   6280:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6281:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6282:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6283:         %timerintchk, %timerintenv);
                   6284: 
1.1162    raeburn  6285:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6286:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6287:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6288:     }
1.1169    droeschl 6289: 
1.1162    raeburn  6290:     foreach my $key (keys(%timerinterval)) {
                   6291:         my ($cid,$rest) = split(/\0/,$key);
                   6292:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6293:     }
1.1169    droeschl 6294: 
1.11      www      6295:     my %allroles=();
1.1162    raeburn  6296:     my %allgroups=();
1.11      www      6297: 
1.1172.2.58  raeburn  6298:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6299:         my $role = $rolesdump{$area};
                   6300:         $area =~ s/\_\w\w$//;
                   6301: 
                   6302:         my ($trole, $tend, $tstart, $group_privs);
                   6303: 
                   6304:         if ($role =~ /^cr/) {
                   6305:         # Custom role, defined by a user 
                   6306:         # e.g., user.role.cr/msu/smith/mynewrole
                   6307:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6308:                 $trole = $1;
                   6309:                 ($tend, $tstart) = split('_', $2);
                   6310:             } else {
                   6311:                 $trole = $role;
                   6312:             }
                   6313:         } elsif ($role =~ m|^gr/|) {
                   6314:         # Role of member in a group, defined within a course/community
                   6315:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6316:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6317:             next if $tstart eq '-1';
                   6318:             ($trole, $group_privs) = split(/\//, $trole);
                   6319:             $group_privs = &unescape($group_privs);
                   6320:         } else {
                   6321:         # Just a normal role, defined in roles.tab
                   6322:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6323:         }
                   6324: 
                   6325:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6326:                  $username);
                   6327:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6328: 
                   6329:         # role expired or not available yet?
                   6330:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6331:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6332: 
                   6333:         next if $area eq '' or $trole eq '';
                   6334: 
                   6335:         my $spec = "$trole.$area";
                   6336:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6337: 
                   6338:         if ($trole =~ /^cr\//) {
                   6339:         # Custom role, defined by a user
                   6340:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6341:         } elsif ($trole eq 'gr') {
                   6342:         # Role of a member in a group, defined within a course/community
                   6343:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6344:             next;
                   6345:         } else {
                   6346:         # Normal role, defined in roles.tab
                   6347:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6348:         }
                   6349: 
                   6350:         my $cid = $tdomain.'_'.$trest;
                   6351:         unless ($firstaccchk{$cid}) {
                   6352:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6353:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6354:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6355:                         $coursetimerstarts{$cid}{$item}; 
                   6356:                 }
                   6357:             }
                   6358:             $firstaccchk{$cid} = 1;
                   6359:         }
                   6360:         unless ($timerintchk{$cid}) {
                   6361:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6362:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6363:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6364:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6365:                 }
1.12      www      6366:             }
1.1169    droeschl 6367:             $timerintchk{$cid} = 1;
1.191     harris41 6368:         }
1.11      www      6369:     }
1.1169    droeschl 6370: 
1.1172.2.91  raeburn  6371:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6372:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6373:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6374:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6375: 
1.1162    raeburn  6376:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6377: }
                   6378: 
1.567     raeburn  6379: sub set_arearole {
1.1172.2.19  raeburn  6380:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6381:     unless ($nolog) {
1.567     raeburn  6382: # log the associated role with the area
1.1172.2.19  raeburn  6383:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6384:     }
1.743     albertel 6385:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6386: }
                   6387: 
                   6388: sub custom_roleprivs {
                   6389:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6390:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6391:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6392:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6393:         my ($rdummy,$roledef)=
                   6394:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6395:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6396:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6397:             if (defined($syspriv)) {
1.1043    raeburn  6398:                 if ($trest =~ /^$match_community$/) {
                   6399:                     $syspriv =~ s/bre\&S//; 
                   6400:                 }
1.567     raeburn  6401:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6402:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6403:             }
                   6404:             if ($tdomain ne '') {
                   6405:                 if (defined($dompriv)) {
                   6406:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6407:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6408:                 }
                   6409:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6410:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6411:                         my $rolename = $1;
                   6412:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6413:                     }
1.567     raeburn  6414:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6415:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6416:                 }
                   6417:             }
                   6418:         }
                   6419:     }
                   6420: }
                   6421: 
1.1172.2.89  raeburn  6422: sub course_adhocrole_privs {
                   6423:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6424:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6425:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6426:         my (%currprivs,%storeprivs);
                   6427:         foreach my $item (split(/:/,$coursepriv)) {
                   6428:             my ($priv,$restrict) = split(/\&/,$item);
                   6429:             $currprivs{$priv} = $restrict;
                   6430:         }
                   6431:         my (%possadd,%possremove,%full);
                   6432:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6433:             my ($priv,$restrict)=split(/\&/,$item);
                   6434:             $full{$priv} = $restrict;
                   6435:         }
                   6436:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6437:              next if ($item eq '');
                   6438:              my ($rule,$rest) = split(/=/,$item);
                   6439:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6440:              foreach my $priv (split(/:/,$rest)) {
                   6441:                  if ($priv ne '') {
                   6442:                      if ($rule eq 'off') {
                   6443:                          $possremove{$priv} = 1;
                   6444:                      } else {
                   6445:                          $possadd{$priv} = 1;
                   6446:                      }
                   6447:                  }
                   6448:              }
                   6449:          }
                   6450:          foreach my $priv (sort(keys(%full))) {
                   6451:              if (exists($currprivs{$priv})) {
                   6452:                  unless (exists($possremove{$priv})) {
                   6453:                      $storeprivs{$priv} = $currprivs{$priv};
                   6454:                  }
                   6455:              } elsif (exists($possadd{$priv})) {
                   6456:                  $storeprivs{$priv} = $full{$priv};
                   6457:              }
                   6458:          }
                   6459:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6460:      }
                   6461:      return $coursepriv;
                   6462: }
                   6463: 
1.678     raeburn  6464: sub group_roleprivs {
                   6465:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6466:     my $access = 1;
                   6467:     my $now = time;
                   6468:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6469:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6470:     if ($access) {
1.811     albertel 6471:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6472:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6473:     }
                   6474: }
1.567     raeburn  6475: 
                   6476: sub standard_roleprivs {
                   6477:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6478:     if (defined($pr{$trole.':s'})) {
                   6479:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6480:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6481:     }
                   6482:     if ($tdomain ne '') {
                   6483:         if (defined($pr{$trole.':d'})) {
                   6484:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6485:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6486:         }
                   6487:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6488:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6489:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6490:         }
                   6491:     }
                   6492: }
                   6493: 
                   6494: sub set_userprivs {
1.1064    raeburn  6495:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6496:     my $author=0;
                   6497:     my $adv=0;
1.1172.2.91  raeburn  6498:     my $rar=0;
1.678     raeburn  6499:     my %grouproles = ();
                   6500:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6501:         my @groupkeys; 
1.1000    raeburn  6502:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6503:             push(@groupkeys,$role);
                   6504:         }
                   6505:         if (ref($groups_roles) eq 'HASH') {
                   6506:             foreach my $key (keys(%{$groups_roles})) {
                   6507:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6508:                     push(@groupkeys,$key);
                   6509:                 }
                   6510:             }
                   6511:         }
                   6512:         if (@groupkeys > 0) {
                   6513:             foreach my $role (@groupkeys) {
                   6514:                 my ($trole,$area,$sec,$extendedarea);
                   6515:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6516:                     $trole = $1;
                   6517:                     $area = $2;
                   6518:                     $sec = $3;
                   6519:                     $extendedarea = $area.$sec;
                   6520:                     if (exists($$allgroups{$area})) {
                   6521:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6522:                             my $spec = $trole.'.'.$extendedarea;
                   6523:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6524:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6525:                         }
1.678     raeburn  6526:                     }
                   6527:                 }
                   6528:             }
                   6529:         }
                   6530:     }
1.800     albertel 6531:     foreach my $group (keys(%grouproles)) {
                   6532:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6533:     }
1.800     albertel 6534:     foreach my $role (keys(%{$allroles})) {
                   6535:         my %thesepriv;
1.941     raeburn  6536:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6537:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6538:             if ($item ne '') {
                   6539:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6540:                 if ($restrictions eq '') {
                   6541:                     $thesepriv{$privilege}='F';
                   6542:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6543:                     $thesepriv{$privilege}.=$restrictions;
                   6544:                 }
                   6545:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6546:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6547:             }
                   6548:         }
                   6549:         my $thesestr='';
1.1104    raeburn  6550:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6551: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6552: 	}
                   6553:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6554:     }
1.1172.2.91  raeburn  6555:     return ($author,$adv,$rar);
1.567     raeburn  6556: }
                   6557: 
1.994     raeburn  6558: sub role_status {
1.1104    raeburn  6559:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6560:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6561:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6562:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6563:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6564:             $$where = '/'.$two;
1.994     raeburn  6565:             $$trolecode=$$role.'.'.$$where;
                   6566:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6567:             $$tstatus='is';
1.1104    raeburn  6568:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6569:                 $$tstatus='future';
1.1034    raeburn  6570:                 if ($$tstart<$now) {
                   6571:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6572:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6573:                             my (%allroles,%allgroups,$group_privs,
                   6574:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6575:                             my %userroles = (
                   6576:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6577:                             );
1.1064    raeburn  6578:                             @rolecodes = ('cm'); 
1.1002    raeburn  6579:                             my $spec=$$role.'.'.$$where;
                   6580:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6581:                             if ($$role =~ /^cr\//) {
                   6582:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6583:                                 push(@rolecodes,'cr');
1.1002    raeburn  6584:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6585:                                 push(@rolecodes,$$role);
1.1002    raeburn  6586:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6587:                                                     $env{'user.name'});
1.1064    raeburn  6588:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6589:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6590:                                 $group_privs = &unescape($group_privs);
                   6591:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6592:                                 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  6593:                                 &get_groups_roles($tdomain,$trest,
                   6594:                                                   \%course_roles,\@rolecodes,
                   6595:                                                   \%groups_roles);
1.1002    raeburn  6596:                             } else {
1.1064    raeburn  6597:                                 push(@rolecodes,$$role);
1.1002    raeburn  6598:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6599:                             }
1.1172.2.91  raeburn  6600:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6601:                                                                    \%groups_roles);
1.1064    raeburn  6602:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6603:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6604:                         }
                   6605:                     }
1.1034    raeburn  6606:                     $$tstatus = 'is';
1.1002    raeburn  6607:                 }
1.994     raeburn  6608:             }
                   6609:             if ($$tend) {
1.1104    raeburn  6610:                 if ($$tend<$update) {
1.994     raeburn  6611:                     $$tstatus='expired';
                   6612:                 } elsif ($$tend<$now) {
                   6613:                     $$tstatus='will_not';
                   6614:                 }
                   6615:             }
                   6616:         }
                   6617:     }
                   6618: }
                   6619: 
1.1104    raeburn  6620: sub get_groups_roles {
                   6621:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6622:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6623:                   (ref($rolecodes) eq 'ARRAY') && 
                   6624:                   (ref($groups_roles) eq 'HASH')); 
                   6625:     if (keys(%{$cdom_courseroles}) > 0) {
                   6626:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6627:         if ($cdom ne '' && $cnum ne '') {
                   6628:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6629:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6630:                     my $crsrole = $1;
                   6631:                     my $crssec = $2;
                   6632:                     if ($crsrole =~ /^cr/) {
                   6633:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6634:                             push(@{$rolecodes},'cr');
                   6635:                         }
                   6636:                     } else {
                   6637:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6638:                             push(@{$rolecodes},$crsrole);
                   6639:                         }
                   6640:                     }
                   6641:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6642:                     if ($crssec ne '') {
                   6643:                         $rolekey .= "/$crssec";
                   6644:                     }
                   6645:                     $rolekey .= './';
                   6646:                     $groups_roles->{$rolekey} = $rolecodes;
                   6647:                 }
                   6648:             }
                   6649:         }
                   6650:     }
                   6651:     return;
                   6652: }
                   6653: 
                   6654: sub delete_env_groupprivs {
                   6655:     my ($where,$courseroles,$possroles) = @_;
                   6656:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6657:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6658:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6659:         %{$courseroles->{$udom}} =
                   6660:             &get_my_roles('','','userroles',['active'],
                   6661:                           $possroles,[$udom],1);
                   6662:     }
                   6663:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6664:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6665:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6666:             my $area = '/'.$cdom.'/'.$cnum;
                   6667:             my $privkey = "user.priv.$crsrole.$area";
                   6668:             if ($crssec ne '') {
                   6669:                 $privkey .= '/'.$crssec;
                   6670:             }
                   6671:             $privkey .= ".$area/$group";
                   6672:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6673:         }
                   6674:     }
                   6675:     return;
                   6676: }
                   6677: 
1.994     raeburn  6678: sub check_adhoc_privs {
1.1172.2.86  raeburn  6679:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6680:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6681:     if ($sec) {
                   6682:         $cckey .= '/'.$sec;
                   6683:     }
1.1172.2.9  raeburn  6684:     my $setprivs;
1.994     raeburn  6685:     if ($env{$cckey}) {
                   6686:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6687:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6688:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6689:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6690:             $setprivs = 1;
1.994     raeburn  6691:         }
                   6692:     } else {
1.1172.2.87  raeburn  6693:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6694:         $setprivs = 1;
1.994     raeburn  6695:     }
1.1172.2.9  raeburn  6696:     return $setprivs;
1.994     raeburn  6697: }
                   6698: 
                   6699: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6700: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6701:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6702:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6703:     if ($sec ne '') {
                   6704:         $area .= '/'.$sec;
                   6705:     }
1.994     raeburn  6706:     my $spec = $role.'.'.$area;
                   6707:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6708:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6709:     my %rolehash = ();
1.1172.2.89  raeburn  6710:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6711:         my $rolename = $1;
1.1172.2.84  raeburn  6712:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6713:         my %domdef = &get_domain_defaults($dcdom);
                   6714:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6715:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6716:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6717:             }
                   6718:         }
1.1172.2.84  raeburn  6719:     } else {
                   6720:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6721:     }
1.1172.2.91  raeburn  6722:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6723:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6724:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6725:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6726:         &appenv( {'request.role'        => $spec,
                   6727:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6728:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6729:                  }
                   6730:                );
                   6731:         my $tadv=0;
                   6732:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6733:         &appenv({'request.role.adv'    => $tadv});
                   6734:     }
1.994     raeburn  6735: }
                   6736: 
1.12      www      6737: # --------------------------------------------------------------- get interface
                   6738: 
                   6739: sub get {
1.131     albertel 6740:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6741:    my $items='';
1.800     albertel 6742:    foreach my $item (@$storearr) {
                   6743:        $items.=&escape($item).'&';
1.191     harris41 6744:    }
1.12      www      6745:    $items=~s/\&$//;
1.620     albertel 6746:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6747:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6748:    my $uhome=&homeserver($uname,$udomain);
                   6749: 
1.133     albertel 6750:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6751:    my @pairs=split(/\&/,$rep);
1.273     albertel 6752:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6753:      return @pairs;
                   6754:    }
1.15      www      6755:    my %returnhash=();
1.42      www      6756:    my $i=0;
1.800     albertel 6757:    foreach my $item (@$storearr) {
                   6758:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6759:       $i++;
1.191     harris41 6760:    }
1.15      www      6761:    return %returnhash;
1.27      www      6762: }
                   6763: 
                   6764: # --------------------------------------------------------------- del interface
                   6765: 
                   6766: sub del {
1.133     albertel 6767:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6768:    my $items='';
1.800     albertel 6769:    foreach my $item (@$storearr) {
                   6770:        $items.=&escape($item).'&';
1.191     harris41 6771:    }
1.984     neumanie 6772: 
1.27      www      6773:    $items=~s/\&$//;
1.620     albertel 6774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6775:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6776:    my $uhome=&homeserver($uname,$udomain);
                   6777:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6778: }
                   6779: 
                   6780: # -------------------------------------------------------------- dump interface
                   6781: 
1.1172.2.22  raeburn  6782: sub unserialize {
                   6783:     my ($rep, $escapedkeys) = @_;
                   6784: 
                   6785:     return {} if $rep =~ /^error/;
                   6786: 
                   6787:     my %returnhash=();
                   6788:     foreach my $item (split(/\&/,$rep)) {
                   6789:         my ($key, $value) = split(/=/, $item, 2);
                   6790:         $key = unescape($key) unless $escapedkeys;
                   6791:         next if $key =~ /^error: 2 /;
                   6792:         $returnhash{$key} = &thaw_unescape($value);
                   6793:     }
                   6794:     return \%returnhash;
                   6795: }
                   6796: 
                   6797: # see Lond::dump_with_regexp
                   6798: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6799: sub dump {
1.1172.2.22  raeburn  6800:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6801:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6802:     if (!$uname) { $uname=$env{'user.name'}; }
                   6803:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6804: 
1.1172.2.55  raeburn  6805:     if ($regexp) {
                   6806:         $regexp=&escape($regexp);
                   6807:     } else {
                   6808:         $regexp='.';
                   6809:     }
1.1172.2.22  raeburn  6810:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6811:         # user is hosted on this machine
1.1172.2.55  raeburn  6812:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6813:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6814:         return %{&unserialize($reply, $escapedkeys)};
                   6815:     }
1.1166    raeburn  6816:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6817:     my @pairs=split(/\&/,$rep);
                   6818:     my %returnhash=();
1.1098    foxr     6819:     if (!($rep =~ /^error/ )) {
                   6820: 	foreach my $item (@pairs) {
                   6821: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6822:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6823: 	    next if ($key =~ /^error: 2 /);
                   6824: 	    $returnhash{$key}=&thaw_unescape($value);
                   6825: 	}
1.755     albertel 6826:     }
                   6827:     return %returnhash;
1.407     www      6828: }
                   6829: 
1.1098    foxr     6830: 
1.717     albertel 6831: # --------------------------------------------------------- dumpstore interface
                   6832: 
                   6833: sub dumpstore {
                   6834:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6835:    # same as dump but keys must be escaped. They may contain colon separated
                   6836:    # lists of values that may themself contain colons (e.g. symbs).
                   6837:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6838: }
                   6839: 
1.407     www      6840: # -------------------------------------------------------------- keys interface
                   6841: 
                   6842: sub getkeys {
                   6843:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6844:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6845:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6846:    my $uhome=&homeserver($uname,$udomain);
                   6847:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6848:    my @keyarray=();
1.800     albertel 6849:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6850:       next if ($key =~ /^error: 2 /);
1.800     albertel 6851:       push(@keyarray,&unescape($key));
1.407     www      6852:    }
                   6853:    return @keyarray;
1.318     matthew  6854: }
                   6855: 
1.319     matthew  6856: # --------------------------------------------------------------- currentdump
                   6857: sub currentdump {
1.328     matthew  6858:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6859:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6860:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6861:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6862:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6863:    my $rep;
                   6864: 
                   6865:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6866:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6867:                    $courseid)));
                   6868:    } else {
                   6869:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6870:    }
                   6871: 
1.318     matthew  6872:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6873:    #
1.318     matthew  6874:    my %returnhash=();
1.319     matthew  6875:    #
                   6876:    if ($rep eq "unknown_cmd") { 
                   6877:        # an old lond will not know currentdump
                   6878:        # Do a dump and make it look like a currentdump
1.822     albertel 6879:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6880:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6881:        my %hash = @tmp;
                   6882:        @tmp=();
1.424     matthew  6883:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6884:    } else {
                   6885:        my @pairs=split(/\&/,$rep);
1.800     albertel 6886:        foreach my $pair (@pairs) {
                   6887:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6888:            my ($symb,$param) = split(/:/,$key);
                   6889:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6890:                                                         &thaw_unescape($value);
1.319     matthew  6891:        }
1.191     harris41 6892:    }
1.12      www      6893:    return %returnhash;
1.424     matthew  6894: }
                   6895: 
                   6896: sub convert_dump_to_currentdump{
                   6897:     my %hash = %{shift()};
                   6898:     my %returnhash;
                   6899:     # Code ripped from lond, essentially.  The only difference
                   6900:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6901:     # we might run in to problems with parameter names =~ /^v\./
                   6902:     while (my ($key,$value) = each(%hash)) {
                   6903:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6904: 	$symb  = &unescape($symb);
                   6905: 	$param = &unescape($param);
1.424     matthew  6906:         next if ($v eq 'version' || $symb eq 'keys');
                   6907:         next if (exists($returnhash{$symb}) &&
                   6908:                  exists($returnhash{$symb}->{$param}) &&
                   6909:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6910:         $returnhash{$symb}->{$param}=$value;
                   6911:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6912:     }
                   6913:     #
                   6914:     # Remove all of the keys in the hashes which keep track of
                   6915:     # the version of the parameter.
                   6916:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6917:         # use a foreach because we are going to delete from the hash.
                   6918:         foreach my $key (keys(%$param_hash)) {
                   6919:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6920:         }
                   6921:     }
                   6922:     return \%returnhash;
1.12      www      6923: }
                   6924: 
1.627     albertel 6925: # ------------------------------------------------------ critical inc interface
                   6926: 
                   6927: sub cinc {
                   6928:     return &inc(@_,'critical');
                   6929: }
                   6930: 
1.449     matthew  6931: # --------------------------------------------------------------- inc interface
                   6932: 
                   6933: sub inc {
1.627     albertel 6934:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6935:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6936:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6937:     my $uhome=&homeserver($uname,$udomain);
                   6938:     my $items='';
                   6939:     if (! ref($store)) {
                   6940:         # got a single value, so use that instead
                   6941:         $items = &escape($store).'=&';
                   6942:     } elsif (ref($store) eq 'SCALAR') {
                   6943:         $items = &escape($$store).'=&';        
                   6944:     } elsif (ref($store) eq 'ARRAY') {
                   6945:         $items = join('=&',map {&escape($_);} @{$store});
                   6946:     } elsif (ref($store) eq 'HASH') {
                   6947:         while (my($key,$value) = each(%{$store})) {
                   6948:             $items.= &escape($key).'='.&escape($value).'&';
                   6949:         }
                   6950:     }
                   6951:     $items=~s/\&$//;
1.627     albertel 6952:     if ($critical) {
                   6953: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6954:     } else {
                   6955: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6956:     }
1.449     matthew  6957: }
                   6958: 
1.12      www      6959: # --------------------------------------------------------------- put interface
                   6960: 
                   6961: sub put {
1.134     albertel 6962:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6963:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6964:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6965:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6966:    my $items='';
1.800     albertel 6967:    foreach my $item (keys(%$storehash)) {
                   6968:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6969:    }
1.12      www      6970:    $items=~s/\&$//;
1.134     albertel 6971:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6972: }
                   6973: 
1.631     albertel 6974: # ------------------------------------------------------------ newput interface
                   6975: 
                   6976: sub newput {
                   6977:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6978:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6979:    if (!$uname) { $uname=$env{'user.name'}; }
                   6980:    my $uhome=&homeserver($uname,$udomain);
                   6981:    my $items='';
                   6982:    foreach my $key (keys(%$storehash)) {
                   6983:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6984:    }
                   6985:    $items=~s/\&$//;
                   6986:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6987: }
                   6988: 
                   6989: # ---------------------------------------------------------  putstore interface
                   6990: 
1.524     raeburn  6991: sub putstore {
1.1172.2.59  raeburn  6992:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6993:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6994:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6995:    my $uhome=&homeserver($uname,$udomain);
                   6996:    my $items='';
1.715     albertel 6997:    foreach my $key (keys(%$storehash)) {
                   6998:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6999:    }
1.715     albertel 7000:    $items=~s/\&$//;
1.716     albertel 7001:    my $esc_symb=&escape($symb);
                   7002:    my $esc_v=&escape($version);
1.715     albertel 7003:    my $reply =
1.716     albertel 7004:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7005: 	      $uhome);
1.1172.2.59  raeburn  7006:    if (($tolog) && ($reply eq 'ok')) {
                   7007:        my $namevalue='';
                   7008:        foreach my $key (keys(%{$storehash})) {
                   7009:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7010:        }
                   7011:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7012:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7013:                      '&version='.$esc_v.
                   7014:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7015:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7016:    }
1.715     albertel 7017:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7018:        # gfall back to way things use to be done
1.715     albertel 7019:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7020: 			    $uname);
1.524     raeburn  7021:    }
1.715     albertel 7022:    return $reply;
                   7023: }
                   7024: 
                   7025: sub old_putstore {
1.716     albertel 7026:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7027:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7028:     if (!$uname) { $uname=$env{'user.name'}; }
                   7029:     my $uhome=&homeserver($uname,$udomain);
                   7030:     my %newstorehash;
1.800     albertel 7031:     foreach my $item (keys(%$storehash)) {
                   7032: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7033: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7034:     }
                   7035:     my $items='';
                   7036:     my %allitems = ();
1.800     albertel 7037:     foreach my $item (keys(%newstorehash)) {
                   7038: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7039: 	    my $key = $1.':keys:'.$2;
                   7040: 	    $allitems{$key} .= $3.':';
                   7041: 	}
1.800     albertel 7042: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7043:     }
1.800     albertel 7044:     foreach my $item (keys(%allitems)) {
                   7045: 	$allitems{$item} =~ s/\:$//;
                   7046: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7047:     }
                   7048:     $items=~s/\&$//;
                   7049:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7050: }
                   7051: 
1.47      www      7052: # ------------------------------------------------------ critical put interface
                   7053: 
                   7054: sub cput {
1.134     albertel 7055:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7056:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7057:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7058:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7059:    my $items='';
1.800     albertel 7060:    foreach my $item (keys(%$storehash)) {
                   7061:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7062:    }
1.47      www      7063:    $items=~s/\&$//;
1.134     albertel 7064:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7065: }
                   7066: 
                   7067: # -------------------------------------------------------------- eget interface
                   7068: 
                   7069: sub eget {
1.133     albertel 7070:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7071:    my $items='';
1.800     albertel 7072:    foreach my $item (@$storearr) {
                   7073:        $items.=&escape($item).'&';
1.191     harris41 7074:    }
1.12      www      7075:    $items=~s/\&$//;
1.620     albertel 7076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7077:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7078:    my $uhome=&homeserver($uname,$udomain);
                   7079:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7080:    my @pairs=split(/\&/,$rep);
                   7081:    my %returnhash=();
1.42      www      7082:    my $i=0;
1.800     albertel 7083:    foreach my $item (@$storearr) {
                   7084:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7085:       $i++;
1.191     harris41 7086:    }
1.12      www      7087:    return %returnhash;
                   7088: }
                   7089: 
1.667     albertel 7090: # ------------------------------------------------------------ tmpput interface
                   7091: sub tmpput {
1.802     raeburn  7092:     my ($storehash,$server,$context)=@_;
1.667     albertel 7093:     my $items='';
1.800     albertel 7094:     foreach my $item (keys(%$storehash)) {
                   7095: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7096:     }
                   7097:     $items=~s/\&$//;
1.802     raeburn  7098:     if (defined($context)) {
                   7099:         $items .= ':'.&escape($context);
                   7100:     }
1.667     albertel 7101:     return &reply("tmpput:$items",$server);
                   7102: }
                   7103: 
                   7104: # ------------------------------------------------------------ tmpget interface
                   7105: sub tmpget {
1.688     albertel 7106:     my ($token,$server)=@_;
                   7107:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7108:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7109:     my %returnhash;
1.1172.2.85  raeburn  7110:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7111:         return %returnhash;
                   7112:     }
1.667     albertel 7113:     foreach my $item (split(/\&/,$rep)) {
                   7114: 	my ($key,$value)=split(/=/,$item);
                   7115: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7116:     }
                   7117:     return %returnhash;
                   7118: }
                   7119: 
1.1113    raeburn  7120: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7121: sub tmpdel {
                   7122:     my ($token,$server)=@_;
                   7123:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7124:     return &reply("tmpdel:$token",$server);
                   7125: }
                   7126: 
1.1172.2.13  raeburn  7127: # ------------------------------------------------------------ get_timebased_id
                   7128: 
                   7129: sub get_timebased_id {
                   7130:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7131:         $maxtries) = @_;
                   7132:     my ($newid,$error,$dellock);
                   7133:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7134:         return ('','ok','invalid call to get suffix');
                   7135:     }
                   7136: 
                   7137: # set defaults for any optional args for which values were not supplied
                   7138:     if ($who eq '') {
                   7139:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7140:     }
                   7141:     if (!$locktries) {
                   7142:         $locktries = 3;
                   7143:     }
                   7144:     if (!$maxtries) {
                   7145:         $maxtries = 10;
                   7146:     }
                   7147: 
                   7148:     if (($cdom eq '') || ($cnum eq '')) {
                   7149:         if ($env{'request.course.id'}) {
                   7150:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7151:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7152:         }
                   7153:         if (($cdom eq '') || ($cnum eq '')) {
                   7154:             return ('','ok','call to get suffix not in course context');
                   7155:         }
                   7156:     }
                   7157: 
                   7158: # construct locking item
                   7159:     my $lockhash = {
                   7160:                       $prefix."\0".'locked_'.$keyid => $who,
                   7161:                    };
                   7162:     my $tries = 0;
                   7163: 
                   7164: # attempt to get lock on nohist_$namespace file
                   7165:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7166:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7167:         $tries ++;
                   7168:         sleep 1;
                   7169:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7170:     }
                   7171: 
                   7172: # attempt to get unique identifier, based on current timestamp
                   7173:     if ($gotlock eq 'ok') {
                   7174:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7175:         my $id = time;
                   7176:         $newid = $id;
1.1172.2.56  raeburn  7177:         if ($idtype eq 'addcode') {
                   7178:             $newid .= &sixnum_code();
                   7179:         }
1.1172.2.13  raeburn  7180:         my $idtries = 0;
                   7181:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7182:             if ($idtype eq 'concat') {
                   7183:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7184:             } elsif ($idtype eq 'addcode') {
                   7185:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7186:             } else {
                   7187:                 $newid ++;
                   7188:             }
                   7189:             $idtries ++;
                   7190:         }
                   7191:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7192:             my %new_item =  (
                   7193:                               $prefix."\0".$newid => $who,
                   7194:                             );
                   7195:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7196:                                                  $cdom,$cnum);
                   7197:             if ($putresult ne 'ok') {
                   7198:                 undef($newid);
                   7199:                 $error = 'error saving new item: '.$putresult;
                   7200:             }
                   7201:         } else {
1.1172.2.56  raeburn  7202:              undef($newid);
1.1172.2.13  raeburn  7203:              $error = ('error: no unique suffix available for the new item ');
                   7204:         }
                   7205: #  remove lock
                   7206:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7207:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7208:     } else {
                   7209:         $error = "error: could not obtain lockfile\n";
                   7210:         $dellock = 'ok';
1.1172.2.58  raeburn  7211:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7212:             $dellock = 'nolock';
                   7213:         }
1.1172.2.13  raeburn  7214:     }
                   7215:     return ($newid,$dellock,$error);
                   7216: }
                   7217: 
1.1172.2.56  raeburn  7218: sub sixnum_code {
                   7219:     my $code;
                   7220:     for (0..6) {
                   7221:         $code .= int( rand(9) );
                   7222:     }
                   7223:     return $code;
                   7224: }
                   7225: 
1.765     albertel 7226: # -------------------------------------------------- portfolio access checking
                   7227: 
                   7228: sub portfolio_access {
1.1172.2.77  raeburn  7229:     my ($requrl,$clientip) = @_;
1.765     albertel 7230:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7231:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7232:     if ($result) {
                   7233:         my %setters;
                   7234:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7235:             my ($startblock,$endblock) =
                   7236:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7237:             if ($startblock && $endblock) {
                   7238:                 return 'B';
                   7239:             }
                   7240:         } else {
                   7241:             my ($startblock,$endblock) =
                   7242:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7243:             if ($startblock && $endblock) {
                   7244:                 return 'B';
                   7245:             }
                   7246:         }
                   7247:     }
1.765     albertel 7248:     if ($result eq 'ok') {
1.766     albertel 7249:        return 'F';
1.765     albertel 7250:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7251:        return 'A';
1.765     albertel 7252:     }
1.766     albertel 7253:     return '';
1.765     albertel 7254: }
                   7255: 
                   7256: sub get_portfolio_access {
1.1172.2.77  raeburn  7257:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7258: 
                   7259:     if (!ref($access_hash)) {
                   7260: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7261: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7262: 						   $file_name);
                   7263: 	$access_hash = $access_controls{$file_name};
                   7264:     }
                   7265: 
1.1172.2.77  raeburn  7266:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7267:     my $now = time;
                   7268:     if (ref($access_hash) eq 'HASH') {
                   7269:         foreach my $key (keys(%{$access_hash})) {
                   7270:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7271:             if ($start > $now) {
                   7272:                 next;
                   7273:             }
                   7274:             if ($end && $end<$now) {
                   7275:                 next;
                   7276:             }
                   7277:             if ($scope eq 'public') {
                   7278:                 $public = $key;
                   7279:                 last;
                   7280:             } elsif ($scope eq 'guest') {
                   7281:                 $guest = $key;
                   7282:             } elsif ($scope eq 'domains') {
                   7283:                 push(@domains,$key);
                   7284:             } elsif ($scope eq 'users') {
                   7285:                 push(@users,$key);
                   7286:             } elsif ($scope eq 'course') {
                   7287:                 push(@courses,$key);
                   7288:             } elsif ($scope eq 'group') {
                   7289:                 push(@groups,$key);
1.1172.2.77  raeburn  7290:             } elsif ($scope eq 'ip') {
                   7291:                 push(@ips,$key);
1.765     albertel 7292:             }
                   7293:         }
                   7294:         if ($public) {
                   7295:             return 'ok';
1.1172.2.77  raeburn  7296:         } elsif (@ips > 0) {
                   7297:             my $allowed;
                   7298:             foreach my $ipkey (@ips) {
                   7299:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7300:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7301:                         $allowed = 1;
                   7302:                         last;
                   7303:                     }
                   7304:                 }
                   7305:             }
                   7306:             if ($allowed) {
                   7307:                 return 'ok';
                   7308:             }
1.765     albertel 7309:         }
                   7310:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7311:             if ($guest) {
                   7312:                 return $guest;
                   7313:             }
                   7314:         } else {
                   7315:             if (@domains > 0) {
                   7316:                 foreach my $domkey (@domains) {
                   7317:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7318:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7319:                             return 'ok';
                   7320:                         }
                   7321:                     }
                   7322:                 }
                   7323:             }
                   7324:             if (@users > 0) {
                   7325:                 foreach my $userkey (@users) {
1.865     raeburn  7326:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7327:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7328:                             if (ref($item) eq 'HASH') {
                   7329:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7330:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7331:                                     return 'ok';
                   7332:                                 }
                   7333:                             }
                   7334:                         }
                   7335:                     } 
1.765     albertel 7336:                 }
                   7337:             }
                   7338:             my %roleshash;
                   7339:             my @courses_and_groups = @courses;
                   7340:             push(@courses_and_groups,@groups); 
                   7341:             if (@courses_and_groups > 0) {
                   7342:                 my (%allgroups,%allroles); 
                   7343:                 my ($start,$end,$role,$sec,$group);
                   7344:                 foreach my $envkey (%env) {
1.1060    raeburn  7345:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7346:                         my $cid = $2.'_'.$3; 
                   7347:                         if ($1 eq 'gr') {
                   7348:                             $group = $4;
                   7349:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7350:                         } else {
                   7351:                             if ($4 eq '') {
                   7352:                                 $sec = 'none';
                   7353:                             } else {
                   7354:                                 $sec = $4;
                   7355:                             }
                   7356:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7357:                         }
1.811     albertel 7358:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7359:                         my $cid = $2.'_'.$3;
                   7360:                         if ($4 eq '') {
                   7361:                             $sec = 'none';
                   7362:                         } else {
                   7363:                             $sec = $4;
                   7364:                         }
                   7365:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7366:                     }
                   7367:                 }
                   7368:                 if (keys(%allroles) == 0) {
                   7369:                     return;
                   7370:                 }
                   7371:                 foreach my $key (@courses_and_groups) {
                   7372:                     my %content = %{$$access_hash{$key}};
                   7373:                     my $cnum = $content{'number'};
                   7374:                     my $cdom = $content{'domain'};
                   7375:                     my $cid = $cdom.'_'.$cnum;
                   7376:                     if (!exists($allroles{$cid})) {
                   7377:                         next;
                   7378:                     }    
                   7379:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7380:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7381:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7382:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7383:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7384:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7385:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7386:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7387:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7388:                                         if (grep/^all$/,@sections) {
                   7389:                                             return 'ok';
                   7390:                                         } else {
                   7391:                                             if (grep/^$sec$/,@sections) {
                   7392:                                                 return 'ok';
                   7393:                                             }
                   7394:                                         }
                   7395:                                     }
                   7396:                                 }
                   7397:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7398:                                     if (grep/^none$/,@groups) {
                   7399:                                         return 'ok';
                   7400:                                     }
                   7401:                                 } else {
                   7402:                                     if (grep/^all$/,@groups) {
                   7403:                                         return 'ok';
                   7404:                                     } 
                   7405:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7406:                                         if (grep/^$group$/,@groups) {
                   7407:                                             return 'ok';
                   7408:                                         }
                   7409:                                     }
                   7410:                                 } 
                   7411:                             }
                   7412:                         }
                   7413:                     }
                   7414:                 }
                   7415:             }
                   7416:             if ($guest) {
                   7417:                 return $guest;
                   7418:             }
                   7419:         }
                   7420:     }
                   7421:     return;
                   7422: }
                   7423: 
                   7424: sub course_group_datechecker {
                   7425:     my ($dates,$now,$status) = @_;
                   7426:     my ($start,$end) = split(/\./,$dates);
                   7427:     if (!$start && !$end) {
                   7428:         return 'ok';
                   7429:     }
                   7430:     if (grep/^active$/,@{$status}) {
                   7431:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7432:             return 'ok';
                   7433:         }
                   7434:     }
                   7435:     if (grep/^previous$/,@{$status}) {
                   7436:         if ($end > $now ) {
                   7437:             return 'ok';
                   7438:         }
                   7439:     }
                   7440:     if (grep/^future$/,@{$status}) {
                   7441:         if ($start > $now) {
                   7442:             return 'ok';
                   7443:         }
                   7444:     }
                   7445:     return; 
                   7446: }
                   7447: 
                   7448: sub parse_portfolio_url {
                   7449:     my ($url) = @_;
                   7450: 
                   7451:     my ($type,$udom,$unum,$group,$file_name);
                   7452:     
1.823     albertel 7453:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7454: 	$type = 1;
                   7455:         $udom = $1;
                   7456:         $unum = $2;
                   7457:         $file_name = $3;
1.823     albertel 7458:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7459: 	$type = 2;
                   7460:         $udom = $1;
                   7461:         $unum = $2;
                   7462:         $group = $3;
                   7463:         $file_name = $3.'/'.$4;
                   7464:     }
                   7465:     if (wantarray) {
                   7466: 	return ($type,$udom,$unum,$file_name,$group);
                   7467:     }
                   7468:     return $type;
                   7469: }
                   7470: 
                   7471: sub is_portfolio_url {
                   7472:     my ($url) = @_;
                   7473:     return scalar(&parse_portfolio_url($url));
                   7474: }
                   7475: 
1.798     raeburn  7476: sub is_portfolio_file {
                   7477:     my ($file) = @_;
1.820     raeburn  7478:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7479:         return 1;
                   7480:     }
                   7481:     return;
                   7482: }
                   7483: 
1.976     raeburn  7484: sub usertools_access {
1.1084    raeburn  7485:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7486:     my ($access,%tools);
                   7487:     if ($context eq '') {
                   7488:         $context = 'tools';
                   7489:     }
                   7490:     if ($context eq 'requestcourses') {
                   7491:         %tools = (
                   7492:                       official   => 1,
                   7493:                       unofficial => 1,
1.1006    raeburn  7494:                       community  => 1,
1.1172.2.37  raeburn  7495:                       textbook   => 1,
1.985     raeburn  7496:                  );
1.1172.2.9  raeburn  7497:     } elsif ($context eq 'requestauthor') {
                   7498:         %tools = (
                   7499:                       requestauthor => 1,
                   7500:                  );
1.985     raeburn  7501:     } else {
                   7502:         %tools = (
                   7503:                       aboutme   => 1,
                   7504:                       blog      => 1,
1.1172.2.6  raeburn  7505:                       webdav    => 1,
1.985     raeburn  7506:                       portfolio => 1,
                   7507:                  );
                   7508:     }
1.976     raeburn  7509:     return if (!defined($tools{$tool}));
                   7510: 
1.1172.2.35  raeburn  7511:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7512:         $udom = $env{'user.domain'};
                   7513:         $uname = $env{'user.name'};
                   7514:     }
                   7515: 
1.978     raeburn  7516:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7517:         if ($action ne 'reload') {
1.985     raeburn  7518:             if ($context eq 'requestcourses') {
                   7519:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7520:             } elsif ($context eq 'requestauthor') {
                   7521:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7522:             } else {
                   7523:                 return $env{'environment.availabletools.'.$tool};
                   7524:             }
                   7525:         }
1.976     raeburn  7526:     }
                   7527: 
1.1172.2.9  raeburn  7528:     my ($toolstatus,$inststatus,$envkey);
                   7529:     if ($context eq 'requestauthor') {
                   7530:         $envkey = $context;
                   7531:     } else {
                   7532:         $envkey = $context.'.'.$tool;
                   7533:     }
1.976     raeburn  7534: 
1.985     raeburn  7535:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7536:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7537:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7538:         $inststatus = $env{'environment.inststatus'};
                   7539:     } else {
1.1084    raeburn  7540:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7541:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7542:             $inststatus = $userenvref->{'inststatus'};
                   7543:         } else {
1.1172.2.9  raeburn  7544:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7545:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7546:             $inststatus = $userenv{'inststatus'};
                   7547:         }
1.976     raeburn  7548:     }
                   7549: 
                   7550:     if ($toolstatus ne '') {
                   7551:         if ($toolstatus) {
                   7552:             $access = 1;
                   7553:         } else {
                   7554:             $access = 0;
                   7555:         }
                   7556:         return $access;
                   7557:     }
                   7558: 
1.1084    raeburn  7559:     my ($is_adv,%domdef);
                   7560:     if (ref($is_advref) eq 'HASH') {
                   7561:         $is_adv = $is_advref->{'is_adv'};
                   7562:     } else {
                   7563:         $is_adv = &is_advanced_user($udom,$uname);
                   7564:     }
                   7565:     if (ref($domdefref) eq 'HASH') {
                   7566:         %domdef = %{$domdefref};
                   7567:     } else {
                   7568:         %domdef = &get_domain_defaults($udom);
                   7569:     }
1.976     raeburn  7570:     if (ref($domdef{$tool}) eq 'HASH') {
                   7571:         if ($is_adv) {
                   7572:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7573:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7574:                     $access = 1;
                   7575:                 } else {
                   7576:                     $access = 0;
                   7577:                 }
                   7578:                 return $access;
                   7579:             }
                   7580:         }
                   7581:         if ($inststatus ne '') {
                   7582:             my ($hasaccess,$hasnoaccess);
                   7583:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7584:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7585:                     if ($domdef{$tool}{$affiliation}) {
                   7586:                         $hasaccess = 1;
                   7587:                     } else {
                   7588:                         $hasnoaccess = 1;
                   7589:                     }
                   7590:                 }
                   7591:             }
                   7592:             if ($hasaccess || $hasnoaccess) {
                   7593:                 if ($hasaccess) {
                   7594:                     $access = 1;
                   7595:                 } elsif ($hasnoaccess) {
                   7596:                     $access = 0; 
                   7597:                 }
                   7598:                 return $access;
                   7599:             }
                   7600:         } else {
                   7601:             if ($domdef{$tool}{'default'} ne '') {
                   7602:                 if ($domdef{$tool}{'default'}) {
                   7603:                     $access = 1;
                   7604:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7605:                     $access = 0;
                   7606:                 }
                   7607:                 return $access;
                   7608:             }
                   7609:         }
                   7610:     } else {
1.1172.2.6  raeburn  7611:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7612:             $access = 1;
                   7613:         } else {
                   7614:             $access = 0;
                   7615:         }
1.976     raeburn  7616:         return $access;
                   7617:     }
                   7618: }
                   7619: 
1.1050    raeburn  7620: sub is_course_owner {
                   7621:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7622:     if (($udom eq '') || ($uname eq '')) {
                   7623:         $udom = $env{'user.domain'};
                   7624:         $uname = $env{'user.name'};
                   7625:     }
                   7626:     unless (($udom eq '') || ($uname eq '')) {
                   7627:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7628:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7629:                 return 1;
                   7630:             } else {
                   7631:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7632:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7633:                     return 1;
                   7634:                 }
                   7635:             }
                   7636:         }
                   7637:     }
                   7638:     return;
                   7639: }
                   7640: 
1.976     raeburn  7641: sub is_advanced_user {
                   7642:     my ($udom,$uname) = @_;
1.1085    raeburn  7643:     if ($udom ne '' && $uname ne '') {
                   7644:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7645:             if (wantarray) {
                   7646:                 return ($env{'user.adv'},$env{'user.author'});
                   7647:             } else {
                   7648:                 return $env{'user.adv'};
                   7649:             }
1.1085    raeburn  7650:         }
                   7651:     }
1.976     raeburn  7652:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7653:     my %allroles;
1.1128    raeburn  7654:     my ($is_adv,$is_author);
1.976     raeburn  7655:     foreach my $role (keys(%roleshash)) {
                   7656:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7657:         my $area = '/'.$tdomain.'/'.$trest;
                   7658:         if ($sec ne '') {
                   7659:             $area .= '/'.$sec;
                   7660:         }
                   7661:         if (($area ne '') && ($trole ne '')) {
                   7662:             my $spec=$trole.'.'.$area;
                   7663:             if ($trole =~ /^cr\//) {
                   7664:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7665:             } elsif ($trole ne 'gr') {
                   7666:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7667:             }
1.1128    raeburn  7668:             if ($trole eq 'au') {
                   7669:                 $is_author = 1;
                   7670:             }
1.976     raeburn  7671:         }
                   7672:     }
                   7673:     foreach my $role (keys(%allroles)) {
                   7674:         last if ($is_adv);
                   7675:         foreach my $item (split(/:/,$allroles{$role})) {
                   7676:             if ($item ne '') {
                   7677:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7678:                 if ($privilege eq 'adv') {
                   7679:                     $is_adv = 1;
                   7680:                     last;
                   7681:                 }
                   7682:             }
                   7683:         }
                   7684:     }
1.1128    raeburn  7685:     if (wantarray) {
                   7686:         return ($is_adv,$is_author);
                   7687:     }
1.976     raeburn  7688:     return $is_adv;
                   7689: }
1.798     raeburn  7690: 
1.1035    raeburn  7691: sub check_can_request {
1.1036    raeburn  7692:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7693:     my $canreq = 0;
                   7694:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7695:     my @options = ('approval','validate','autolimit');
                   7696:     my $optregex = join('|',@options);
                   7697:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7698:         foreach my $type (@{$types}) {
                   7699:             if (&usertools_access($env{'user.name'},
                   7700:                                   $env{'user.domain'},
                   7701:                                   $type,undef,'requestcourses')) {
                   7702:                 $canreq ++;
1.1036    raeburn  7703:                 if (ref($request_domains) eq 'HASH') {
                   7704:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7705:                 }
1.1035    raeburn  7706:                 if ($dom eq $env{'user.domain'}) {
                   7707:                     $can_request->{$type} = 1;
                   7708:                 }
                   7709:             }
                   7710:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7711:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7712:                 if (@curr > 0) {
1.1036    raeburn  7713:                     foreach my $item (@curr) {
                   7714:                         if (ref($request_domains) eq 'HASH') {
                   7715:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7716:                             if ($otherdom ne '') {
                   7717:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7718:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7719:                                         push(@{$request_domains->{$type}},$otherdom);
                   7720:                                     }
                   7721:                                 } else {
                   7722:                                     push(@{$request_domains->{$type}},$otherdom);
                   7723:                                 }
                   7724:                             }
                   7725:                         }
                   7726:                     }
                   7727:                     unless($dom eq $env{'user.domain'}) {
                   7728:                         $canreq ++;
1.1035    raeburn  7729:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7730:                             $can_request->{$type} = 1;
                   7731:                         }
                   7732:                     }
                   7733:                 }
                   7734:             }
                   7735:         }
                   7736:     }
                   7737:     return $canreq;
                   7738: }
                   7739: 
1.341     www      7740: # ---------------------------------------------- Custom access rule evaluation
                   7741: 
                   7742: sub customaccess {
                   7743:     my ($priv,$uri)=@_;
1.807     albertel 7744:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7745:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7746:     $udom = &LONCAPA::clean_domain($udom);
                   7747:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7748:     my $access=0;
1.800     albertel 7749:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7750: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7751: 	if ($type eq 'user') {
                   7752: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7753: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7754: 		if ($tdom) {
                   7755: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7756: 		}
1.896     albertel 7757: 		if ($tuname) {
                   7758: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7759: 		}
                   7760: 		$access=($effect eq 'allow');
                   7761: 		last;
                   7762: 	    }
                   7763: 	} else {
                   7764: 	    if ($role) {
                   7765: 		if ($role ne $urole) { next; }
                   7766: 	    }
                   7767: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7768: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7769: 		if ($tdom) {
                   7770: 		    if ($tdom ne $udom) { next; }
                   7771: 		}
                   7772: 		if ($tcrs) {
                   7773: 		    if ($tcrs ne $ucrs) { next; }
                   7774: 		}
                   7775: 		if ($tsec) {
                   7776: 		    if ($tsec ne $usec) { next; }
                   7777: 		}
                   7778: 		$access=($effect eq 'allow');
                   7779: 		last;
                   7780: 	    }
                   7781: 	    if ($realm eq '' && $role eq '') {
                   7782: 		$access=($effect eq 'allow');
                   7783: 	    }
1.402     bowersj2 7784: 	}
1.341     www      7785:     }
                   7786:     return $access;
                   7787: }
                   7788: 
1.103     harris41 7789: # ------------------------------------------------- Check for a user privilege
1.12      www      7790: 
                   7791: sub allowed {
1.1172.2.65  raeburn  7792:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7793:     my $ver_orguri=$uri;
1.439     www      7794:     $uri=&deversion($uri);
1.152     www      7795:     my $orguri=$uri;
1.52      www      7796:     $uri=&declutter($uri);
1.809     raeburn  7797: 
1.810     raeburn  7798:     if ($priv eq 'evb') {
                   7799: # Evade communication block restrictions for specified role in a course
                   7800:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7801:             return $1;
                   7802:         } else {
                   7803:             return;
                   7804:         }
                   7805:     }
                   7806: 
1.620     albertel 7807:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7808: # Free bre access to adm and meta resources
1.775     albertel 7809:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7810: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7811: 	&& ($priv eq 'bre')) {
1.14      www      7812: 	return 'F';
1.159     www      7813:     }
                   7814: 
1.545     banghart 7815: # Free bre access to user's own portfolio contents
1.714     raeburn  7816:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7817:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7818: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7819:         my %setters;
                   7820:         my ($startblock,$endblock) = 
                   7821:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7822:         if ($startblock && $endblock) {
                   7823:             return 'B';
                   7824:         } else {
                   7825:             return 'F';
                   7826:         }
1.545     banghart 7827:     }
                   7828: 
1.762     raeburn  7829: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7830:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7831:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7832:         if (exists($env{'request.course.id'})) {
                   7833:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7834:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7835:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7836:                 my $courseprivid=$env{'request.course.id'};
                   7837:                 $courseprivid=~s/\_/\//;
                   7838:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7839:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7840:                     return $1; 
1.762     raeburn  7841:                 } else {
                   7842:                     if ($env{'request.course.sec'}) {
                   7843:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7844:                     }
                   7845:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7846:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7847:                         return $2;
                   7848:                     }
1.714     raeburn  7849:                 }
                   7850:             }
                   7851:         }
                   7852:     }
                   7853: 
1.159     www      7854: # Free bre to public access
                   7855: 
                   7856:     if ($priv eq 'bre') {
1.238     www      7857:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7858: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7859:            return 'F'; 
                   7860:         }
1.238     www      7861:         if ($copyright eq 'priv') {
                   7862:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7863: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7864: 		return '';
                   7865:             }
                   7866:         }
                   7867:         if ($copyright eq 'domain') {
                   7868:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7869: 	    unless (($env{'user.domain'} eq $1) ||
                   7870:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7871: 		return '';
                   7872:             }
1.262     matthew  7873:         }
1.620     albertel 7874:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7875:             # Library role, so allow browsing of resources in this domain.
                   7876:             return 'F';
1.238     www      7877:         }
1.341     www      7878:         if ($copyright eq 'custom') {
                   7879: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7880:         }
1.14      www      7881:     }
1.264     matthew  7882:     # Domain coordinator is trying to create a course
1.620     albertel 7883:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7884:         # uri is the requested domain in this case.
                   7885:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7886:         # a role of dc for the domain in question.
1.620     albertel 7887:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7888:     }
1.29      www      7889: 
1.52      www      7890:     my $thisallowed='';
                   7891:     my $statecond=0;
                   7892:     my $courseprivid='';
                   7893: 
1.1039    raeburn  7894:     my $ownaccess;
1.1043    raeburn  7895:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7896:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7897:         if ($uri eq '') {
                   7898:             $ownaccess = 1;
                   7899:         } else {
                   7900:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7901:                 my $udom = $env{'user.domain'};
                   7902:                 my $uname = $env{'user.name'};
                   7903:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7904:                     $ownaccess = 1;
1.1040    raeburn  7905:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7906:                     unless ($uri =~ m{\.\./}) {
                   7907:                         $ownaccess = 1;
                   7908:                     }
                   7909:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7910:                     my $now = time;
                   7911:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7912:                         my $adom = $1;
                   7913:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7914:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7915:                                 my ($start,$end) = split('.',$env{$key});
                   7916:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7917:                                     $ownaccess = 1;
                   7918:                                     last;
                   7919:                                 }
                   7920:                             }
                   7921:                         }
                   7922:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7923:                         my $adom = $1;
                   7924:                         my $aname = $2;
1.1042    raeburn  7925:                         foreach my $role ('ca','aa') { 
                   7926:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7927:                                 my ($start,$end) =
                   7928:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7929:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7930:                                     $ownaccess = 1;
                   7931:                                     last;
                   7932:                                 }
1.1039    raeburn  7933:                             }
                   7934:                         }
                   7935:                     }
                   7936:                 }
                   7937:             }
                   7938:         }
                   7939:     }
                   7940: 
1.52      www      7941: # Course
                   7942: 
1.620     albertel 7943:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7944:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7945:             $thisallowed.=$1;
                   7946:         }
1.52      www      7947:     }
1.29      www      7948: 
1.52      www      7949: # Domain
                   7950: 
1.620     albertel 7951:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7952:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7953:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7954:             $thisallowed.=$1;
                   7955:         }
1.12      www      7956:     }
1.52      www      7957: 
1.1141    raeburn  7958: # User who is not author or co-author might still be able to edit
                   7959: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7960:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7961:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7962:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7963:             $thisallowed.=$1;
                   7964:         }
                   7965:     }
                   7966: 
1.52      www      7967: # Course: uri itself is a course
1.66      www      7968:     my $courseuri=$uri;
                   7969:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7970:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7971: 
1.620     albertel 7972:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7973:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7974:         if ($priv eq 'mip') {
                   7975:             my $rem = $1;
                   7976:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7977:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7978:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7979:                 if ($cdom ne '') {
                   7980:                     my %passwdconf = &get_passwdconf($cdom);
                   7981:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7982:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7983:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7984:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7985:                                 unless (@inststatuses) {
                   7986:                                     @inststatuses = ('default');
                   7987:                                 }
                   7988:                                 foreach my $status (@inststatuses) {
                   7989:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   7990:                                         $thisallowed.=$rem;
                   7991:                                     }
                   7992:                                 }
                   7993:                             }
                   7994:                         }
                   7995:                     }
                   7996:                 }
                   7997:             }
                   7998:         } else {
                   7999:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8000:                 $thisallowed.=$1;
                   8001:             }
1.1039    raeburn  8002:         }
1.12      www      8003:     }
1.29      www      8004: 
1.665     albertel 8005: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8006: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8007:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8008: 	$thisallowed='';
1.671     raeburn  8009:         my ($match)=&is_on_map($uri);
                   8010:         if ($match) {
                   8011:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8012:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8013:                 my $value = $1;
                   8014:                 if ($noblockcheck) {
                   8015:                     $thisallowed.=$value;
1.1162    raeburn  8016:                 } else {
1.1172.2.65  raeburn  8017:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8018:                     if (@blockers > 0) {
                   8019:                         $thisallowed = 'B';
                   8020:                     } else {
                   8021:                         $thisallowed.=$value;
                   8022:                     }
1.1162    raeburn  8023:                 }
1.671     raeburn  8024:             }
                   8025:         } else {
1.705     albertel 8026:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8027:             if ($refuri) {
                   8028:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8029:                     $thisallowed='F';
1.671     raeburn  8030:                 } else {
                   8031:                     $refuri=&declutter($refuri);
                   8032:                     my ($match) = &is_on_map($refuri);
                   8033:                     if ($match) {
1.1172.2.65  raeburn  8034:                         if ($noblockcheck) {
1.1162    raeburn  8035:                             $thisallowed='F';
1.1172.2.65  raeburn  8036:                         } else {
                   8037:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8038:                             if (@blockers > 0) {
                   8039:                                 $thisallowed = 'B';
                   8040:                             } else {
                   8041:                                 $thisallowed='F';
                   8042:                             }
1.1162    raeburn  8043:                         }
1.671     raeburn  8044:                     }
1.669     raeburn  8045:                 }
1.671     raeburn  8046:             }
                   8047:         }
1.314     www      8048:     }
1.492     albertel 8049: 
1.766     albertel 8050:     if ($priv eq 'bre'
                   8051: 	&& $thisallowed ne 'F' 
                   8052: 	&& $thisallowed ne '2'
                   8053: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8054: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8055:     }
                   8056:     
1.52      www      8057: # Full access at system, domain or course-wide level? Exit.
1.29      www      8058:     if ($thisallowed=~/F/) {
                   8059: 	return 'F';
                   8060:     }
                   8061: 
1.52      www      8062: # If this is generating or modifying users, exit with special codes
1.29      www      8063: 
1.643     www      8064:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8065: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8066: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8067: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8068: 	    unless ($auname) { return $thisallowed; }
                   8069: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8070: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8071: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8072: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8073: 	}
1.52      www      8074: 	return $thisallowed;
                   8075:     }
                   8076: #
1.103     harris41 8077: # Gathered so far: system, domain and course wide privileges
1.52      www      8078: #
                   8079: # Course: See if uri or referer is an individual resource that is part of 
                   8080: # the course
                   8081: 
1.620     albertel 8082:     if ($env{'request.course.id'}) {
1.232     www      8083: 
1.1172.2.115  raeburn  8084: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8085: 
                   8086:         if ($priv eq 'mip') {
                   8087:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8088:                 return $thisallowed;
                   8089:             } else {
                   8090:                 return '';
                   8091:             }
                   8092:         }
                   8093: 
1.620     albertel 8094:        $courseprivid=$env{'request.course.id'};
                   8095:        if ($env{'request.course.sec'}) {
                   8096:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8097:        }
                   8098:        $courseprivid=~s/\_/\//;
                   8099:        my $checkreferer=1;
1.232     www      8100:        my ($match,$cond)=&is_on_map($uri);
                   8101:        if ($match) {
                   8102:            $statecond=$cond;
1.620     albertel 8103:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8104:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8105:                my $value = $1;
                   8106:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8107:                    if ($noblockcheck) {
1.1162    raeburn  8108:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8109:                    } else {
                   8110:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8111:                        if (@blockers > 0) {
                   8112:                            $thisallowed = 'B';
                   8113:                        } else {
                   8114:                            $thisallowed.=$value;
                   8115:                        }
1.1162    raeburn  8116:                    }
                   8117:                } else {
                   8118:                    $thisallowed.=$value;
                   8119:                }
1.52      www      8120:                $checkreferer=0;
                   8121:            }
1.29      www      8122:        }
1.83      www      8123:        
1.148     www      8124:        if ($checkreferer) {
1.620     albertel 8125: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8126:             unless ($refuri) {
1.800     albertel 8127:                 foreach my $key (keys(%env)) {
                   8128: 		    if ($key=~/^httpref\..*\*/) {
                   8129: 			my $pattern=$key;
1.156     www      8130:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8131:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8132:                         $pattern=~s/\//\\\//g;
1.152     www      8133:                         if ($orguri=~/$pattern/) {
1.800     albertel 8134: 			    $refuri=$env{$key};
1.148     www      8135:                         }
                   8136:                     }
1.191     harris41 8137:                 }
1.148     www      8138:             }
1.232     www      8139: 
1.148     www      8140:          if ($refuri) { 
1.152     www      8141: 	  $refuri=&declutter($refuri);
1.232     www      8142:           my ($match,$cond)=&is_on_map($refuri);
                   8143:             if ($match) {
                   8144:               my $refstatecond=$cond;
1.620     albertel 8145:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8146:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8147:                   my $value = $1;
                   8148:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8149:                       if ($noblockcheck) {
1.1162    raeburn  8150:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8151:                       } else {
                   8152:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8153:                           if (@blockers > 0) {
                   8154:                               $thisallowed = 'B';
                   8155:                           } else {
                   8156:                               $thisallowed.=$value;
                   8157:                           }
1.1162    raeburn  8158:                       }
                   8159:                   } else {
                   8160:                       $thisallowed.=$value;
                   8161:                   }
1.53      www      8162:                   $uri=$refuri;
                   8163:                   $statecond=$refstatecond;
1.52      www      8164:               }
                   8165:           }
1.148     www      8166:         }
1.29      www      8167:        }
1.52      www      8168:    }
1.29      www      8169: 
1.52      www      8170: #
1.103     harris41 8171: # Gathered now: all privileges that could apply, and condition number
1.52      www      8172: # 
                   8173: #
                   8174: # Full or no access?
                   8175: #
1.29      www      8176: 
1.52      www      8177:     if ($thisallowed=~/F/) {
                   8178: 	return 'F';
                   8179:     }
1.29      www      8180: 
1.52      www      8181:     unless ($thisallowed) {
                   8182:         return '';
                   8183:     }
1.29      www      8184: 
1.52      www      8185: # Restrictions exist, deal with them
                   8186: #
                   8187: #   C:according to course preferences
                   8188: #   R:according to resource settings
                   8189: #   L:unless locked
                   8190: #   X:according to user session state
                   8191: #
                   8192: 
                   8193: # Possibly locked functionality, check all courses
1.54      www      8194: # Locks might take effect only after 10 minutes cache expiration for other
                   8195: # courses, and 2 minutes for current course
1.52      www      8196: 
                   8197:     my $envkey;
                   8198:     if ($thisallowed=~/L/) {
1.1000    raeburn  8199:         foreach $envkey (keys(%env)) {
1.54      www      8200:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8201:                my $courseid=$2;
                   8202:                my $roleid=$1.'.'.$2;
1.92      www      8203:                $courseid=~s/^\///;
1.54      www      8204:                my $expiretime=600;
1.620     albertel 8205:                if ($env{'request.role'} eq $roleid) {
1.54      www      8206: 		  $expiretime=120;
                   8207:                }
                   8208: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8209:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8210:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8211: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8212:                }
1.620     albertel 8213:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8214:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8215: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8216:                        &log($env{'user.domain'},$env{'user.name'},
                   8217:                             $env{'user.home'},
1.57      www      8218:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8219:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8220:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8221: 		       return '';
                   8222:                    }
                   8223:                }
1.620     albertel 8224:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8225:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8226: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8227:                        &log($env{'user.domain'},$env{'user.name'},
                   8228:                             $env{'user.home'},
1.57      www      8229:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8230:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8231:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8232: 		       return '';
                   8233:                    }
                   8234:                }
                   8235: 	   }
1.29      www      8236:        }
1.52      www      8237:     }
                   8238:    
                   8239: #
                   8240: # Rest of the restrictions depend on selected course
                   8241: #
                   8242: 
1.620     albertel 8243:     unless ($env{'request.course.id'}) {
1.766     albertel 8244: 	if ($thisallowed eq 'A') {
                   8245: 	    return 'A';
1.814     raeburn  8246:         } elsif ($thisallowed eq 'B') {
                   8247:             return 'B';
1.766     albertel 8248: 	} else {
                   8249: 	    return '1';
                   8250: 	}
1.52      www      8251:     }
1.29      www      8252: 
1.52      www      8253: #
                   8254: # Now user is definitely in a course
                   8255: #
1.53      www      8256: 
                   8257: 
                   8258: # Course preferences
                   8259: 
                   8260:    if ($thisallowed=~/C/) {
1.620     albertel 8261:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8262:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8263:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8264: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8265: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8266: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8267: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8268: 			$env{'request.course.id'});
                   8269: 	   }
1.237     www      8270:            return '';
                   8271:        }
                   8272: 
1.620     albertel 8273:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8274: 	   =~/\Q$unamedom\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 user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8278: 			$env{'request.course.id'});
                   8279: 	   }
1.54      www      8280:            return '';
                   8281:        }
1.53      www      8282:    }
                   8283: 
                   8284: # Resource preferences
                   8285: 
                   8286:    if ($thisallowed=~/R/) {
1.620     albertel 8287:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8288:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8289: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8290: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8291: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8292: 	   }
                   8293: 	   return '';
1.54      www      8294:        }
1.53      www      8295:    }
1.30      www      8296: 
1.246     www      8297: # Restricted by state or randomout?
1.30      www      8298: 
1.52      www      8299:    if ($thisallowed=~/X/) {
1.620     albertel 8300:       if ($env{'acc.randomout'}) {
1.579     albertel 8301: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8302:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8303:             return ''; 
                   8304:          }
1.247     www      8305:       }
                   8306:       if (&condval($statecond)) {
1.52      www      8307: 	 return '2';
                   8308:       } else {
                   8309:          return '';
                   8310:       }
                   8311:    }
1.30      www      8312: 
1.766     albertel 8313:     if ($thisallowed eq 'A') {
                   8314: 	return 'A';
1.814     raeburn  8315:     } elsif ($thisallowed eq 'B') {
                   8316:         return 'B';
1.766     albertel 8317:     }
1.52      www      8318:    return 'F';
1.232     www      8319: }
1.1162    raeburn  8320: 
1.1172.2.13  raeburn  8321: # ------------------------------------------- Check construction space access
                   8322: 
                   8323: sub constructaccess {
                   8324:     my ($url,$setpriv)=@_;
                   8325: 
                   8326: # We do not allow editing of previous versions of files
                   8327:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8328: 
                   8329: # Get username and domain from URL
                   8330:     my ($ownername,$ownerdomain,$ownerhome);
                   8331: 
                   8332:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8333:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8334: 
                   8335: # The URL does not really point to any authorspace, forget it
                   8336:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8337: 
                   8338: # Now we need to see if the user has access to the authorspace of
                   8339: # $ownername at $ownerdomain
                   8340: 
                   8341:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8342: # Real author for this?
                   8343:        $ownerhome = $env{'user.home'};
                   8344:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8345:           return ($ownername,$ownerdomain,$ownerhome);
                   8346:        }
                   8347:     } else {
                   8348: # Co-author for this?
                   8349:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8350:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8351:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8352:             return ($ownername,$ownerdomain,$ownerhome);
                   8353:         }
                   8354:     }
                   8355: 
                   8356: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8357: # we might as well leave
                   8358:    unless ($setpriv) { return ''; }
                   8359: 
                   8360: # Backdoor access?
                   8361:     my $allowed=&allowed('eco',$ownerdomain);
                   8362: # Nope
                   8363:     unless ($allowed) { return ''; }
                   8364: # Looks like we may have access, but could be locked by the owner of the construction space
                   8365:     if ($allowed eq 'U') {
                   8366:         my %blocked=&get('environment',['domcoord.author'],
                   8367:                          $ownerdomain,$ownername);
                   8368: # Is blocked by owner
                   8369:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8370:     }
                   8371:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8372: # Grant temporary access
                   8373:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8374:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8375:         if (!$update) { $update = $then; }
                   8376:         my $refresh=$env{'user.refresh.time'};
                   8377:         if (!$refresh) { $refresh = $update; }
                   8378:         my $now = time;
                   8379:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8380:                            $now,'ca','constructaccess');
                   8381:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8382:         return($ownername,$ownerdomain,$ownerhome);
                   8383:     }
                   8384: # No business here
                   8385:     return '';
                   8386: }
                   8387: 
1.1172.2.66  raeburn  8388: # ----------------------------------------------------------- Content Blocking
                   8389: 
                   8390: {
                   8391: # Caches for faster Course Contents display where content blocking
                   8392: # is in operation (i.e., interval param set) for timed quiz.
                   8393: #
                   8394: # User for whom data are being temporarily cached.
                   8395: my $cacheduser='';
                   8396: # Cached blockers for this user (a hash of blocking items).
                   8397: my %cachedblockers=();
                   8398: # When the data were last cached.
                   8399: my $cachedlast='';
                   8400: 
                   8401: sub load_all_blockers {
                   8402:     my ($uname,$udom,$blocks)=@_;
                   8403:     if (($uname ne '') && ($udom ne '')) {
                   8404:         if (($cacheduser eq $uname.':'.$udom) &&
                   8405:             (abs($cachedlast-time)<5)) {
                   8406:             return;
                   8407:         }
                   8408:     }
                   8409:     $cachedlast=time;
                   8410:     $cacheduser=$uname.':'.$udom;
                   8411:     %cachedblockers = &get_commblock_resources($blocks);
                   8412: }
                   8413: 
1.1162    raeburn  8414: sub get_comm_blocks {
                   8415:     my ($cdom,$cnum) = @_;
                   8416:     if ($cdom eq '' || $cnum eq '') {
                   8417:         return unless ($env{'request.course.id'});
                   8418:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8419:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8420:     }
                   8421:     my %commblocks;
                   8422:     my $hashid=$cdom.'_'.$cnum;
                   8423:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8424:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8425:         %commblocks = %{$blocksref};
                   8426:     } else {
                   8427:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8428:         my $cachetime = 600;
                   8429:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8430:     }
                   8431:     return %commblocks;
                   8432: }
                   8433: 
1.1172.2.66  raeburn  8434: sub get_commblock_resources {
                   8435:     my ($blocks) = @_;
                   8436:     my %blockers = ();
                   8437:     return %blockers unless ($env{'request.course.id'});
                   8438:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8439:     my %commblocks;
                   8440:     if (ref($blocks) eq 'HASH') {
                   8441:         %commblocks = %{$blocks};
                   8442:     } else {
                   8443:         %commblocks = &get_comm_blocks();
                   8444:     }
1.1172.2.66  raeburn  8445:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8446:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8447:     return %blockers unless (ref($navmap));
                   8448:     my $now = time;
1.1162    raeburn  8449:     foreach my $block (keys(%commblocks)) {
                   8450:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8451:             my ($start,$end) = ($1,$2);
                   8452:             if ($start <= $now && $end >= $now) {
                   8453:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8454:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8455:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8456:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8457:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8458:                             }
                   8459:                         }
                   8460:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8461:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8462:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8463:                             }
                   8464:                         }
                   8465:                     }
                   8466:                 }
                   8467:             }
                   8468:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8469:             my $item = $1;
1.1163    raeburn  8470:             my @to_test;
1.1162    raeburn  8471:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8472:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8473:                     my @interval;
                   8474:                     my $type = 'map';
                   8475:                     if ($item eq 'course') {
                   8476:                         $type = 'course';
                   8477:                         @interval=&EXT("resource.0.interval");
                   8478:                     } else {
                   8479:                         if ($item =~ /___\d+___/) {
                   8480:                             $type = 'resource';
                   8481:                             @interval=&EXT("resource.0.interval",$item);
                   8482:                             if (ref($navmap)) {
                   8483:                                 my $res = $navmap->getBySymb($item);
                   8484:                                 push(@to_test,$res);
                   8485:                             }
1.1162    raeburn  8486:                         } else {
1.1172.2.66  raeburn  8487:                             my $mapsymb = &symbread($item,1);
                   8488:                             if ($mapsymb) {
                   8489:                                 if (ref($navmap)) {
                   8490:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8491:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8492:                                     foreach my $res (@to_test) {
                   8493:                                         my $symb = $res->symb();
                   8494:                                         next if ($symb eq $mapsymb);
                   8495:                                         if ($symb ne '') {
                   8496:                                             @interval=&EXT("resource.0.interval",$symb);
                   8497:                                             if ($interval[1] eq 'map') {
                   8498:                                                 last;
1.1162    raeburn  8499:                                             }
                   8500:                                         }
                   8501:                                     }
                   8502:                                 }
                   8503:                             }
                   8504:                         }
1.1172.2.66  raeburn  8505:                     }
                   8506:                     if ($interval[0] =~ /^\d+$/) {
                   8507:                         my $first_access;
                   8508:                         if ($type eq 'resource') {
                   8509:                             $first_access=&get_first_access($interval[1],$item);
                   8510:                         } elsif ($type eq 'map') {
                   8511:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8512:                         } else {
                   8513:                             $first_access=&get_first_access($interval[1]);
                   8514:                         }
                   8515:                         if ($first_access) {
                   8516:                             my $timesup = $first_access+$interval[0];
                   8517:                             if ($timesup > $now) {
                   8518:                                 my $activeblock;
                   8519:                                 foreach my $res (@to_test) {
                   8520:                                     if ($res->answerable()) {
                   8521:                                         $activeblock = 1;
                   8522:                                         last;
                   8523:                                     }
                   8524:                                 }
                   8525:                                 if ($activeblock) {
                   8526:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8527:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8528:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8529:                                          }
                   8530:                                     }
                   8531:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8532:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8533:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8534:                                         }
1.1162    raeburn  8535:                                     }
                   8536:                                 }
                   8537:                             }
                   8538:                         }
                   8539:                     }
                   8540:                 }
                   8541:             }
                   8542:         }
                   8543:     }
1.1172.2.66  raeburn  8544:     return %blockers;
1.1162    raeburn  8545: }
                   8546: 
1.1172.2.66  raeburn  8547: sub has_comm_blocking {
                   8548:     my ($priv,$symb,$uri,$blocks) = @_;
                   8549:     my @blockers;
                   8550:     return unless ($env{'request.course.id'});
                   8551:     return unless ($priv eq 'bre');
                   8552:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8553:     return if ($env{'request.state'} eq 'construct');
                   8554:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8555:     return unless (keys(%cachedblockers) > 0);
                   8556:     my (%possibles,@symbs);
                   8557:     if (!$symb) {
                   8558:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8559:     }
1.1172.2.66  raeburn  8560:     if ($symb) {
                   8561:         @symbs = ($symb);
                   8562:     } elsif (keys(%possibles)) {
                   8563:         @symbs = keys(%possibles);
                   8564:     }
                   8565:     my $noblock;
                   8566:     foreach my $symb (@symbs) {
                   8567:         last if ($noblock);
                   8568:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8569:         foreach my $block (keys(%cachedblockers)) {
                   8570:             if ($block =~ /^firstaccess____(.+)$/) {
                   8571:                 my $item = $1;
                   8572:                 if (($item eq $map) || ($item eq $symb)) {
                   8573:                     $noblock = 1;
                   8574:                     last;
                   8575:                 }
1.1162    raeburn  8576:             }
1.1172.2.66  raeburn  8577:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8578:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8579:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8580:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8581:                             push(@blockers,$block);
                   8582:                         }
                   8583:                     }
                   8584:                 }
                   8585:             }
                   8586:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8587:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8588:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8589:                         push(@blockers,$block);
                   8590:                     }
                   8591:                 }
1.1162    raeburn  8592:             }
                   8593:         }
                   8594:     }
1.1172.2.66  raeburn  8595:     return if ($noblock);
                   8596:     return @blockers;
                   8597: }
1.1162    raeburn  8598: }
                   8599: 
1.1172.2.66  raeburn  8600: # -------------------------------- Deversion and split uri into path an filename
                   8601: 
1.1133    foxr     8602: #
1.1172.2.66  raeburn  8603: #   Removes the version from a URI and
1.1133    foxr     8604: #   splits it in to its filename and path to the filename.
                   8605: #   Seems like File::Basename could have done this more clearly.
                   8606: #   Parameters:
                   8607: #      $uri   - input URI
                   8608: #   Returns:
                   8609: #     Two element list consisting of 
                   8610: #     $pathname  - the URI up to and excluding the trailing /
                   8611: #     $filename  - The part of the URI following the last /
                   8612: #  NOTE:
                   8613: #    Another realization of this is simply:
                   8614: #    use File::Basename;
                   8615: #    ...
                   8616: #    $uri = shift;
                   8617: #    $filename = basename($uri);
                   8618: #    $path     = dirname($uri);
                   8619: #    return ($filename, $path);
                   8620: #
                   8621: #     The implementation below is probably faster however.
                   8622: #
1.710     albertel 8623: sub split_uri_for_cond {
                   8624:     my $uri=&deversion(&declutter(shift));
                   8625:     my @uriparts=split(/\//,$uri);
                   8626:     my $filename=pop(@uriparts);
                   8627:     my $pathname=join('/',@uriparts);
                   8628:     return ($pathname,$filename);
                   8629: }
1.232     www      8630: # --------------------------------------------------- Is a resource on the map?
                   8631: 
                   8632: sub is_on_map {
1.710     albertel 8633:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8634:     #Trying to find the conditional for the file
1.620     albertel 8635:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8636: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8637:     if ($match) {
1.289     bowersj2 8638: 	return (1,$1);
                   8639:     } else {
1.434     www      8640: 	return (0,0);
1.289     bowersj2 8641:     }
1.12      www      8642: }
                   8643: 
1.427     www      8644: # --------------------------------------------------------- Get symb from alias
                   8645: 
                   8646: sub get_symb_from_alias {
                   8647:     my $symb=shift;
                   8648:     my ($map,$resid,$url)=&decode_symb($symb);
                   8649: # Already is a symb
                   8650:     if ($url) { return $symb; }
                   8651: # Must be an alias
                   8652:     my $aliassymb='';
                   8653:     my %bighash;
1.620     albertel 8654:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8655:                             &GDBM_READER(),0640)) {
                   8656:         my $rid=$bighash{'mapalias_'.$symb};
                   8657: 	if ($rid) {
                   8658: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8659: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8660: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8661: 	}
                   8662:         untie %bighash;
                   8663:     }
                   8664:     return $aliassymb;
                   8665: }
                   8666: 
1.12      www      8667: # ----------------------------------------------------------------- Define Role
                   8668: 
                   8669: sub definerole {
                   8670:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8671:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8672:     foreach my $role (split(':',$sysrole)) {
                   8673: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8674:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8675:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8676: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8677:                return "refused:s:$crole&$cqual"; 
                   8678:             }
                   8679:         }
1.191     harris41 8680:     }
1.800     albertel 8681:     foreach my $role (split(':',$domrole)) {
                   8682: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8683:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8684:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8685: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8686:                return "refused:d:$crole&$cqual"; 
                   8687:             }
                   8688:         }
1.191     harris41 8689:     }
1.800     albertel 8690:     foreach my $role (split(':',$courole)) {
                   8691: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8692:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8693:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8694: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8695:                return "refused:c:$crole&$cqual"; 
                   8696:             }
                   8697:         }
1.191     harris41 8698:     }
1.1172.2.84  raeburn  8699:     my $uhome;
                   8700:     if (($uname ne '') && ($udom ne '')) {
                   8701:         $uhome = &homeserver($uname,$udom);
                   8702:         return $uhome if ($uhome eq 'no_host');
                   8703:     } else {
                   8704:         $uname = $env{'user.name'};
                   8705:         $udom = $env{'user.domain'};
                   8706:         $uhome = $env{'user.home'};
                   8707:     }
1.620     albertel 8708:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8709:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8710:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8711:     return reply($command,$uhome);
1.12      www      8712:   } else {
                   8713:     return 'refused';
                   8714:   }
1.105     harris41 8715: }
                   8716: 
                   8717: # ---------------- Make a metadata query against the network of library servers
                   8718: 
                   8719: sub metadata_query {
1.1172.2.33  raeburn  8720:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8721:     my %rhash;
1.845     albertel 8722:     my %libserv = &all_library();
1.244     matthew  8723:     my @server_list = (defined($server_array) ? @$server_array
                   8724:                                               : keys(%libserv) );
                   8725:     for my $server (@server_list) {
1.1172.2.33  raeburn  8726:         my $domains = '';
                   8727:         if (ref($domains_hash) eq 'HASH') {
                   8728:             $domains = $domains_hash->{$server};    
                   8729:         }
1.118     harris41 8730: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8731: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8732: 	    $rhash{$server}=$reply;
                   8733: 	}
                   8734: 	else {
                   8735: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8736: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8737: 			     $server);
                   8738: 	    $rhash{$server}=$reply;
                   8739: 	}
1.112     harris41 8740:     }
1.118     harris41 8741:     return \%rhash;
1.240     www      8742: }
                   8743: 
                   8744: # ----------------------------------------- Send log queries and wait for reply
                   8745: 
                   8746: sub log_query {
                   8747:     my ($uname,$udom,$query,%filters)=@_;
                   8748:     my $uhome=&homeserver($uname,$udom);
                   8749:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8750:     my $uhost=&hostname($uhome);
1.800     albertel 8751:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8752:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8753:                        $uhome);
1.479     albertel 8754:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8755:     return get_query_reply($queryid);
                   8756: }
                   8757: 
1.818     raeburn  8758: # -------------------------- Update MySQL table for portfolio file
                   8759: 
                   8760: sub update_portfolio_table {
1.821     raeburn  8761:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8762:     if ($group ne '') {
                   8763:         $file_name =~s /^\Q$group\E//;
                   8764:     }
1.818     raeburn  8765:     my $homeserver = &homeserver($uname,$udom);
                   8766:     my $queryid=
1.821     raeburn  8767:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8768:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8769:     my $reply = &get_query_reply($queryid);
                   8770:     return $reply;
                   8771: }
                   8772: 
1.899     raeburn  8773: # -------------------------- Update MySQL allusers table
                   8774: 
                   8775: sub update_allusers_table {
                   8776:     my ($uname,$udom,$names) = @_;
                   8777:     my $homeserver = &homeserver($uname,$udom);
                   8778:     my $queryid=
                   8779:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8780:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8781:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8782:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8783:                'generation='.&escape($names->{'generation'}).'%%'.
                   8784:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8785:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8786:     return;
1.899     raeburn  8787: }
                   8788: 
1.508     raeburn  8789: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8790: 
                   8791: sub fetch_enrollment_query {
1.511     raeburn  8792:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8793:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8794:     my $maxtries = 1;
1.508     raeburn  8795:     if ($context eq 'automated') {
                   8796:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8797:         $sleep = 2;
                   8798:         $loopmax = 100;
1.547     raeburn  8799:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8800:     } else {
                   8801:         $homeserver = &homeserver($cnum,$dom);
                   8802:     }
1.838     albertel 8803:     my $host=&hostname($homeserver);
1.506     raeburn  8804:     my $cmd = '';
1.1000    raeburn  8805:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8806:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8807:     }
                   8808:     $cmd =~ s/%%$//;
                   8809:     $cmd = &escape($cmd);
                   8810:     my $query = 'fetchenrollment';
1.620     albertel 8811:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8812:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8813:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8814:         return 'error: '.$queryid;
                   8815:     }
1.1172.2.93  raeburn  8816:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8817:     my $tries = 1;
                   8818:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8819:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8820:         $tries ++;
                   8821:     }
1.526     raeburn  8822:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8823:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8824:     } else {
1.901     albertel 8825:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8826:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8827:             foreach my $line (@responses) {
                   8828:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8829:                 $$replyref{$key} = $value;
                   8830:             }
                   8831:         } else {
1.1117    foxr     8832:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8833:             foreach my $line (@responses) {
                   8834:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8835:                 $$replyref{$key} = $value;
                   8836:                 if ($value > 0) {
1.800     albertel 8837:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8838:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8839:                         my $destname = $pathname.'/'.$filename;
                   8840:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8841:                         if ($xml_classlist =~ /^error/) {
                   8842:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8843:                         } else {
1.1172.2.96  raeburn  8844:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8845:                                 print FILE &unescape($xml_classlist);
                   8846:                                 close(FILE);
1.526     raeburn  8847:                             } else {
                   8848:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8849:                             }
                   8850:                         }
                   8851:                     }
                   8852:                 }
                   8853:             }
                   8854:         }
                   8855:         return 'ok';
                   8856:     }
                   8857:     return 'error';
                   8858: }
                   8859: 
1.242     www      8860: sub get_query_reply {
1.1172.2.79  raeburn  8861:     my ($queryid,$sleep,$loopmax) = @_;
                   8862:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8863:         $sleep = 0.2;
                   8864:     }
                   8865:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8866:         $loopmax = 100;
                   8867:     }
1.1117    foxr     8868:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8869:     my $reply='';
1.1172.2.79  raeburn  8870:     for (1..$loopmax) {
                   8871: 	sleep($sleep);
1.240     www      8872:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8873: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8874: 		$reply = join('',<$fh>);
                   8875: 		close($fh);
1.240     www      8876: 	   } else { return 'error: reply_file_error'; }
1.242     www      8877:            return &unescape($reply);
                   8878: 	}
1.240     www      8879:     }
1.242     www      8880:     return 'timeout:'.$queryid;
1.240     www      8881: }
                   8882: 
                   8883: sub courselog_query {
1.241     www      8884: #
                   8885: # possible filters:
                   8886: # url: url or symb
                   8887: # username
                   8888: # domain
                   8889: # action: view, submit, grade
                   8890: # start: timestamp
                   8891: # end: timestamp
                   8892: #
1.240     www      8893:     my (%filters)=@_;
1.620     albertel 8894:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8895:     if ($filters{'url'}) {
                   8896: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8897:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8898:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8899:     }
1.620     albertel 8900:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8901:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8902:     return &log_query($cname,$cdom,'courselog',%filters);
                   8903: }
                   8904: 
                   8905: sub userlog_query {
1.858     raeburn  8906: #
                   8907: # possible filters:
                   8908: # action: log check role
                   8909: # start: timestamp
                   8910: # end: timestamp
                   8911: #
1.240     www      8912:     my ($uname,$udom,%filters)=@_;
                   8913:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8914: }
                   8915: 
1.506     raeburn  8916: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8917: 
                   8918: sub auto_run {
1.508     raeburn  8919:     my ($cnum,$cdom) = @_;
1.876     raeburn  8920:     my $response = 0;
                   8921:     my $settings;
                   8922:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8923:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8924:         $settings = $domconfig{'autoenroll'};
                   8925:         if ($settings->{'run'} eq '1') {
                   8926:             $response = 1;
                   8927:         }
                   8928:     } else {
1.934     raeburn  8929:         my $homeserver;
                   8930:         if (&is_course($cdom,$cnum)) {
                   8931:             $homeserver = &homeserver($cnum,$cdom);
                   8932:         } else {
                   8933:             $homeserver = &domain($cdom,'primary');
                   8934:         }
                   8935:         if ($homeserver ne 'no_host') {
                   8936:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8937:         }
1.876     raeburn  8938:     }
1.506     raeburn  8939:     return $response;
                   8940: }
1.776     albertel 8941: 
1.506     raeburn  8942: sub auto_get_sections {
1.508     raeburn  8943:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8944:     my $homeserver;
                   8945:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8946:         $homeserver = &homeserver($cnum,$cdom);
                   8947:     }
                   8948:     if (!defined($homeserver)) { 
                   8949:         if ($cdom =~ /^$match_domain$/) {
                   8950:             $homeserver = &domain($cdom,'primary');
                   8951:         }
                   8952:     }
                   8953:     my @secs;
                   8954:     if (defined($homeserver)) {
                   8955:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8956:         unless ($response eq 'refused') {
                   8957:             @secs = split(/:/,$response);
                   8958:         }
1.506     raeburn  8959:     }
                   8960:     return @secs;
                   8961: }
1.776     albertel 8962: 
1.506     raeburn  8963: sub auto_new_course {
1.1099    raeburn  8964:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8965:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8966:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8967:     return $response;
                   8968: }
1.776     albertel 8969: 
1.506     raeburn  8970: sub auto_validate_courseID {
1.508     raeburn  8971:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8972:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8973:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8974:     return $response;
                   8975: }
1.776     albertel 8976: 
1.1007    raeburn  8977: sub auto_validate_instcode {
1.1020    raeburn  8978:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8979:     my ($homeserver,$response);
                   8980:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8981:         $homeserver = &homeserver($cnum,$cdom);
                   8982:     }
                   8983:     if (!defined($homeserver)) {
                   8984:         if ($cdom =~ /^$match_domain$/) {
                   8985:             $homeserver = &domain($cdom,'primary');
                   8986:         }
                   8987:     }
1.1065    raeburn  8988:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8989:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8990:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8991:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8992: }
                   8993: 
1.506     raeburn  8994: sub auto_create_password {
1.873     raeburn  8995:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8996:     my ($homeserver,$response);
1.506     raeburn  8997:     my $create_passwd = 0;
                   8998:     my $authchk = '';
1.873     raeburn  8999:     if ($udom =~ /^$match_domain$/) {
                   9000:         $homeserver = &domain($udom,'primary');
                   9001:     }
                   9002:     if ($homeserver eq '') {
                   9003:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9004:             $homeserver = &homeserver($cnum,$cdom);
                   9005:         }
                   9006:     }
                   9007:     if ($homeserver eq '') {
                   9008:         $authchk = 'nodomain';
1.506     raeburn  9009:     } else {
1.873     raeburn  9010:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9011:         if ($response eq 'refused') {
                   9012:             $authchk = 'refused';
                   9013:         } else {
1.901     albertel 9014:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9015:         }
1.506     raeburn  9016:     }
                   9017:     return ($authparam,$create_passwd,$authchk);
                   9018: }
                   9019: 
1.706     raeburn  9020: sub auto_photo_permission {
                   9021:     my ($cnum,$cdom,$students) = @_;
                   9022:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9023:     my ($outcome,$perm_reqd,$conditions) = 
                   9024: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9025:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9026: 	return (undef,undef);
                   9027:     }
1.706     raeburn  9028:     return ($outcome,$perm_reqd,$conditions);
                   9029: }
                   9030: 
                   9031: sub auto_checkphotos {
                   9032:     my ($uname,$udom,$pid) = @_;
                   9033:     my $homeserver = &homeserver($uname,$udom);
                   9034:     my ($result,$resulttype);
                   9035:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9036: 				   &escape($uname).':'.&escape($pid),
                   9037: 				   $homeserver));
1.709     albertel 9038:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9039: 	return (undef,undef);
                   9040:     }
1.706     raeburn  9041:     if ($outcome) {
                   9042:         ($result,$resulttype) = split(/:/,$outcome);
                   9043:     } 
                   9044:     return ($result,$resulttype);
                   9045: }
                   9046: 
                   9047: sub auto_photochoice {
                   9048:     my ($cnum,$cdom) = @_;
                   9049:     my $homeserver = &homeserver($cnum,$cdom);
                   9050:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9051: 						       &escape($cdom),
                   9052: 						       $homeserver)));
1.709     albertel 9053:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9054: 	return (undef,undef);
                   9055:     }
1.706     raeburn  9056:     return ($update,$comment);
                   9057: }
                   9058: 
                   9059: sub auto_photoupdate {
                   9060:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9061:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9062:     my $host=&hostname($homeserver);
1.706     raeburn  9063:     my $cmd = '';
                   9064:     my $maxtries = 1;
1.800     albertel 9065:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9066:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9067:     }
                   9068:     $cmd =~ s/%%$//;
                   9069:     $cmd = &escape($cmd);
                   9070:     my $query = 'institutionalphotos';
                   9071:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9072:     unless ($queryid=~/^\Q$host\E\_/) {
                   9073:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9074:         return 'error: '.$queryid;
                   9075:     }
                   9076:     my $reply = &get_query_reply($queryid);
                   9077:     my $tries = 1;
                   9078:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9079:         $reply = &get_query_reply($queryid);
                   9080:         $tries ++;
                   9081:     }
                   9082:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9083:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9084:     } else {
                   9085:         my @responses = split(/:/,$reply);
                   9086:         my $outcome = shift(@responses); 
                   9087:         foreach my $item (@responses) {
                   9088:             my ($key,$value) = split(/=/,$item);
                   9089:             $$photo{$key} = $value;
                   9090:         }
                   9091:         return $outcome;
                   9092:     }
                   9093:     return 'error';
                   9094: }
                   9095: 
1.521     raeburn  9096: sub auto_instcode_format {
1.793     albertel 9097:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9098: 	$cat_order) = @_;
1.521     raeburn  9099:     my $courses = '';
1.772     raeburn  9100:     my @homeservers;
1.521     raeburn  9101:     if ($caller eq 'global') {
1.841     albertel 9102: 	my %servers = &get_servers($codedom,'library');
                   9103: 	foreach my $tryserver (keys(%servers)) {
                   9104: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9105: 		push(@homeservers,$tryserver);
                   9106: 	    }
1.584     raeburn  9107:         }
1.1022    raeburn  9108:     } elsif ($caller eq 'requests') {
                   9109:         if ($codedom =~ /^$match_domain$/) {
                   9110:             my $chome = &domain($codedom,'primary');
                   9111:             unless ($chome eq 'no_host') {
                   9112:                 push(@homeservers,$chome);
                   9113:             }
                   9114:         }
1.521     raeburn  9115:     } else {
1.772     raeburn  9116:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9117:     }
1.793     albertel 9118:     foreach my $code (keys(%{$instcodes})) {
                   9119:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9120:     }
                   9121:     chop($courses);
1.772     raeburn  9122:     my $ok_response = 0;
                   9123:     my $response;
                   9124:     while (@homeservers > 0 && $ok_response == 0) {
                   9125:         my $server = shift(@homeservers); 
                   9126:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9127:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9128:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9129: 		split(/:/,$response);
1.772     raeburn  9130:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9131:             push(@{$codetitles},&str2array($codetitles_str));
                   9132:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9133:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9134:             $ok_response = 1;
                   9135:         }
                   9136:     }
                   9137:     if ($ok_response) {
1.521     raeburn  9138:         return 'ok';
1.772     raeburn  9139:     } else {
                   9140:         return $response;
1.521     raeburn  9141:     }
                   9142: }
                   9143: 
1.792     raeburn  9144: sub auto_instcode_defaults {
                   9145:     my ($domain,$returnhash,$code_order) = @_;
                   9146:     my @homeservers;
1.841     albertel 9147: 
                   9148:     my %servers = &get_servers($domain,'library');
                   9149:     foreach my $tryserver (keys(%servers)) {
                   9150: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9151: 	    push(@homeservers,$tryserver);
                   9152: 	}
1.792     raeburn  9153:     }
1.841     albertel 9154: 
1.792     raeburn  9155:     my $response;
1.841     albertel 9156:     foreach my $server (@homeservers) {
1.792     raeburn  9157:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9158:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9159: 	
                   9160: 	foreach my $pair (split(/\&/,$response)) {
                   9161: 	    my ($name,$value)=split(/\=/,$pair);
                   9162: 	    if ($name eq 'code_order') {
                   9163: 		@{$code_order} = split(/\&/,&unescape($value));
                   9164: 	    } else {
                   9165: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9166: 	    }
                   9167: 	}
                   9168: 	return 'ok';
1.792     raeburn  9169:     }
1.841     albertel 9170: 
                   9171:     return $response;
1.1003    raeburn  9172: }
                   9173: 
                   9174: sub auto_possible_instcodes {
1.1007    raeburn  9175:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9176:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9177:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9178:         return;
                   9179:     }
1.1003    raeburn  9180:     my (@homeservers,$uhome);
                   9181:     if (defined(&domain($domain,'primary'))) {
                   9182:         $uhome=&domain($domain,'primary');
                   9183:         push(@homeservers,&domain($domain,'primary'));
                   9184:     } else {
                   9185:         my %servers = &get_servers($domain,'library');
                   9186:         foreach my $tryserver (keys(%servers)) {
                   9187:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9188:                 push(@homeservers,$tryserver);
                   9189:             }
                   9190:         }
                   9191:     }
                   9192:     my $response;
                   9193:     foreach my $server (@homeservers) {
                   9194:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9195:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9196:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9197:             split(':',$response);
                   9198:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9199:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9200:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9201:             my ($name,$value)=split('=',$item);
                   9202:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9203:         }
                   9204:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9205:             my ($name,$value)=split('=',$item);
                   9206:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9207:         }
                   9208:         return 'ok';
                   9209:     }
                   9210:     return $response;
                   9211: }
1.792     raeburn  9212: 
1.1010    raeburn  9213: sub auto_courserequest_checks {
                   9214:     my ($dom) = @_;
1.1020    raeburn  9215:     my ($homeserver,%validations);
                   9216:     if ($dom =~ /^$match_domain$/) {
                   9217:         $homeserver = &domain($dom,'primary');
                   9218:     }
                   9219:     unless ($homeserver eq 'no_host') {
                   9220:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9221:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9222:             my @items = split(/&/,$response);
                   9223:             foreach my $item (@items) {
                   9224:                 my ($key,$value) = split('=',$item);
                   9225:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9226:             }
                   9227:         }
                   9228:     }
1.1010    raeburn  9229:     return %validations; 
                   9230: }
                   9231: 
1.1020    raeburn  9232: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9233:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9234:     my ($homeserver,$response);
                   9235:     if ($dom =~ /^$match_domain$/) {
                   9236:         $homeserver = &domain($dom,'primary');
                   9237:     }
1.1172.2.43  raeburn  9238:     unless ($homeserver eq 'no_host') {
                   9239:         my $customdata;
                   9240:         if (ref($custominfo) eq 'HASH') {
                   9241:             $customdata = &freeze_escape($custominfo);
                   9242:         }
1.1020    raeburn  9243:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9244:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9245:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9246:                                     $customdata,$homeserver));
1.1020    raeburn  9247:     }
                   9248:     return $response;
                   9249: }
                   9250: 
1.777     albertel 9251: sub auto_validate_class_sec {
1.918     raeburn  9252:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9253:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9254:     my $ownerlist;
                   9255:     if (ref($owners) eq 'ARRAY') {
                   9256:         $ownerlist = join(',',@{$owners});
                   9257:     } else {
                   9258:         $ownerlist = $owners;
                   9259:     }
1.773     raeburn  9260:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9261:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9262:     return $response;
                   9263: }
                   9264: 
1.1172.2.94  raeburn  9265: sub auto_validate_instclasses {
                   9266:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9267:     my ($homeserver,%validations);
                   9268:     $homeserver = &homeserver($cnum,$cdom);
                   9269:     unless ($homeserver eq 'no_host') {
                   9270:         my $ownerlist;
                   9271:         if (ref($owners) eq 'ARRAY') {
                   9272:             $ownerlist = join(',',@{$owners});
                   9273:         } else {
                   9274:             $ownerlist = $owners;
                   9275:         }
                   9276:         if (ref($classesref) eq 'HASH') {
                   9277:             my $classes = &freeze_escape($classesref);
                   9278:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9279:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9280:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9281:                 my @items = split(/&/,$response);
                   9282:                 foreach my $item (@items) {
                   9283:                     my ($key,$value) = split('=',$item);
                   9284:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9285:                 }
                   9286:             }
                   9287:         }
                   9288:     }
                   9289:     return %validations;
                   9290: }
                   9291: 
1.1172.2.38  raeburn  9292: sub auto_crsreq_update {
                   9293:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9294:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9295:     my ($homeserver,%crsreqresponse);
                   9296:     if ($cdom =~ /^$match_domain$/) {
                   9297:         $homeserver = &domain($cdom,'primary');
                   9298:     }
                   9299:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9300:         my $info;
                   9301:         if (ref($inbound) eq 'HASH') {
                   9302:             $info = &freeze_escape($inbound);
                   9303:         }
                   9304:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9305:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9306:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9307:                             &escape($title).':'.&escape($code).':'.
                   9308:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9309:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9310:             my @items = split(/&/,$response);
                   9311:             foreach my $item (@items) {
                   9312:                 my ($key,$value) = split('=',$item);
                   9313:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9314:             }
                   9315:         }
                   9316:     }
                   9317:     return \%crsreqresponse;
                   9318: }
                   9319: 
1.1172.2.78  raeburn  9320: sub auto_export_grades {
                   9321:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9322:     my ($homeserver,%exportresponse);
                   9323:     if ($cdom =~ /^$match_domain$/) {
                   9324:         $homeserver = &domain($cdom,'primary');
                   9325:     }
                   9326:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9327:         my $info;
                   9328:         if (ref($inforef) eq 'HASH') {
                   9329:             $info = &freeze_escape($inforef);
                   9330:         }
                   9331:         if (ref($gradesref) eq 'HASH') {
                   9332:             my $grades = &freeze_escape($gradesref);
                   9333:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9334:                                 $info.':'.$grades,$homeserver);
                   9335:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9336:                 my @items = split(/&/,$response);
                   9337:                 foreach my $item (@items) {
                   9338:                     my ($key,$value) = split('=',$item);
                   9339:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9340:                 }
                   9341:             }
                   9342:         }
                   9343:     }
                   9344:     return \%exportresponse;
                   9345: }
                   9346: 
1.1172.2.68  raeburn  9347: sub check_instcode_cloning {
                   9348:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9349:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9350:         return;
                   9351:     }
                   9352:     my $canclone;
                   9353:     if (@{$code_order} > 0) {
                   9354:         my $instcoderegexp ='^';
                   9355:         my @clonecodes = split(/\&/,$cloner);
                   9356:         foreach my $item (@{$code_order}) {
                   9357:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9358:                 foreach my $pair (@clonecodes) {
                   9359:                     my ($key,$val) = split(/\=/,$pair,2);
                   9360:                     $val = &unescape($val);
                   9361:                     if ($key eq $item) {
                   9362:                         $instcoderegexp .= '('.$val.')';
                   9363:                         last;
                   9364:                     }
                   9365:                 }
                   9366:             } else {
                   9367:                 $instcoderegexp .= $codedefaults->{$item};
                   9368:             }
                   9369:         }
                   9370:         $instcoderegexp .= '$';
                   9371:         my (@from,@to);
                   9372:         eval {
                   9373:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9374:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9375:         };
                   9376:         if ((@from > 0) && (@to > 0)) {
                   9377:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9378:             if (!@diffs) {
                   9379:                 $canclone = 1;
                   9380:             }
                   9381:         }
                   9382:     }
                   9383:     return $canclone;
                   9384: }
                   9385: 
                   9386: sub default_instcode_cloning {
                   9387:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9388:     my (%codedefaults,@code_order,$canclone);
                   9389:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9390:         %codedefaults = %{$codedefaultsref};
                   9391:         @code_order = @{$codeorderref};
                   9392:     } elsif ($clonedom) {
                   9393:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9394:     }
                   9395:     if (($domdefclone) && (@code_order)) {
                   9396:         my @clonecodes = split(/\+/,$domdefclone);
                   9397:         my $instcoderegexp ='^';
                   9398:         foreach my $item (@code_order) {
                   9399:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9400:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9401:             } else {
                   9402:                 $instcoderegexp .= $codedefaults{$item};
                   9403:             }
                   9404:         }
                   9405:         $instcoderegexp .= '$';
                   9406:         my (@from,@to);
                   9407:         eval {
                   9408:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9409:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9410:         };
                   9411:         if ((@from > 0) && (@to > 0)) {
                   9412:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9413:             if (!@diffs) {
                   9414:                 $canclone = 1;
                   9415:             }
                   9416:         }
                   9417:     }
                   9418:     return $canclone;
                   9419: }
                   9420: 
1.679     raeburn  9421: # ------------------------------------------------------- Course Group routines
                   9422: 
                   9423: sub get_coursegroups {
1.809     raeburn  9424:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9425:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9426: }
                   9427: 
1.679     raeburn  9428: sub modify_coursegroup {
                   9429:     my ($cdom,$cnum,$groupsettings) = @_;
                   9430:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9431: }
                   9432: 
1.809     raeburn  9433: sub toggle_coursegroup_status {
                   9434:     my ($cdom,$cnum,$group,$action) = @_;
                   9435:     my ($from_namespace,$to_namespace);
                   9436:     if ($action eq 'delete') {
                   9437:         $from_namespace = 'coursegroups';
                   9438:         $to_namespace = 'deleted_groups';
                   9439:     } else {
                   9440:         $from_namespace = 'deleted_groups';
                   9441:         $to_namespace = 'coursegroups';
                   9442:     }
                   9443:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9444:     if (my $tmp = &error(%curr_group)) {
                   9445:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9446:         return ('read error',$tmp);
                   9447:     } else {
                   9448:         my %savedsettings = %curr_group; 
1.809     raeburn  9449:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9450:         my $deloutcome;
                   9451:         if ($result eq 'ok') {
1.809     raeburn  9452:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9453:         } else {
                   9454:             return ('write error',$result);
                   9455:         }
                   9456:         if ($deloutcome eq 'ok') {
                   9457:             return 'ok';
                   9458:         } else {
                   9459:             return ('delete error',$deloutcome);
                   9460:         }
                   9461:     }
                   9462: }
                   9463: 
1.679     raeburn  9464: sub modify_group_roles {
1.957     raeburn  9465:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9466:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9467:     my $role = 'gr/'.&escape($userprivs);
                   9468:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9469:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9470:     if ($result eq 'ok') {
                   9471:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9472:     }
1.679     raeburn  9473:     return $result;
                   9474: }
                   9475: 
                   9476: sub modify_coursegroup_membership {
                   9477:     my ($cdom,$cnum,$membership) = @_;
                   9478:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9479:     return $result;
                   9480: }
                   9481: 
1.682     raeburn  9482: sub get_active_groups {
                   9483:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9484:     my $now = time;
                   9485:     my %groups = ();
                   9486:     foreach my $key (keys(%env)) {
1.811     albertel 9487:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9488:             my ($start,$end) = split(/\./,$env{$key});
                   9489:             if (($end!=0) && ($end<$now)) { next; }
                   9490:             if (($start!=0) && ($start>$now)) { next; }
                   9491:             if ($1 eq $cdom && $2 eq $cnum) {
                   9492:                 $groups{$3} = $env{$key} ;
                   9493:             }
                   9494:         }
                   9495:     }
                   9496:     return %groups;
                   9497: }
                   9498: 
1.683     raeburn  9499: sub get_group_membership {
                   9500:     my ($cdom,$cnum,$group) = @_;
                   9501:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9502: }
                   9503: 
                   9504: sub get_users_groups {
                   9505:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9506:     my @usersgroups;
1.683     raeburn  9507:     my $cachetime=1800;
                   9508: 
                   9509:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9510:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9511:     if (defined($cached)) {
1.734     albertel 9512:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9513:     } else {  
                   9514:         $grouplist = '';
1.816     raeburn  9515:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9516:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9517:         my $access_end = $env{'course.'.$courseid.
                   9518:                               '.default_enrollment_end_date'};
                   9519:         my $now = time;
                   9520:         foreach my $key (keys(%roleshash)) {
                   9521:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9522:                 my $group = $1;
                   9523:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9524:                     my $start = $2;
                   9525:                     my $end = $1;
                   9526:                     if ($start == -1) { next; } # deleted from group
                   9527:                     if (($start!=0) && ($start>$now)) { next; }
                   9528:                     if (($end!=0) && ($end<$now)) {
                   9529:                         if ($access_end && $access_end < $now) {
                   9530:                             if ($access_end - $end < 86400) {
                   9531:                                 push(@usersgroups,$group);
1.733     raeburn  9532:                             }
                   9533:                         }
1.817     raeburn  9534:                         next;
1.733     raeburn  9535:                     }
1.817     raeburn  9536:                     push(@usersgroups,$group);
1.683     raeburn  9537:                 }
                   9538:             }
                   9539:         }
1.817     raeburn  9540:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9541:         $grouplist = join(':',@usersgroups);
                   9542:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9543:     }
1.733     raeburn  9544:     return @usersgroups;
1.683     raeburn  9545: }
                   9546: 
                   9547: sub devalidate_getgroups_cache {
                   9548:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9549:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9550: 
1.683     raeburn  9551:     my $hashid="$udom:$uname:$courseid";
                   9552:     &devalidate_cache_new('getgroups',$hashid);
                   9553: }
                   9554: 
1.12      www      9555: # ------------------------------------------------------------------ Plain Text
                   9556: 
                   9557: sub plaintext {
1.988     raeburn  9558:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9559:     if ($short =~ m{^cr/}) {
1.758     albertel 9560: 	return (split('/',$short))[-1];
                   9561:     }
1.742     raeburn  9562:     if (!defined($cid)) {
                   9563:         $cid = $env{'request.course.id'};
                   9564:     }
                   9565:     my %rolenames = (
1.1008    raeburn  9566:                       Course    => 'std',
                   9567:                       Community => 'alt1',
1.742     raeburn  9568:                     );
1.1037    raeburn  9569:     if ($cid ne '') {
                   9570:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9571:             unless ($forcedefault) {
                   9572:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9573:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9574:                 return &Apache::lonlocal::mt($roletext);
                   9575:             }
                   9576:         }
                   9577:     }
                   9578:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9579:         (defined($rolenames{$type})) && 
                   9580:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9581:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9582:     } elsif ($cid ne '') {
                   9583:         my $crstype = $env{'course.'.$cid.'.type'};
                   9584:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9585:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9586:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9587:         }
1.742     raeburn  9588:     }
1.1037    raeburn  9589:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9590: }
                   9591: 
                   9592: # ----------------------------------------------------------------- Assign Role
                   9593: 
                   9594: sub assignrole {
1.957     raeburn  9595:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9596:         $context)=@_;
1.21      www      9597:     my $mrole;
                   9598:     if ($role =~ /^cr\//) {
1.393     www      9599:         my $cwosec=$url;
1.811     albertel 9600:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9601: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9602:            my $refused = 1;
                   9603:            if ($context eq 'requestcourses') {
                   9604:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9605:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9606:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9607:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9608:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9609:                            if ($crsenv{'internal.courseowner'} eq
                   9610:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9611:                                $refused = '';
                   9612:                            }
                   9613:                        }
                   9614:                    }
                   9615:                }
                   9616:            }
                   9617:            if ($refused) {
                   9618:                &logthis('Refused custom assignrole: '.
                   9619:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9620:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9621:                return 'refused';
                   9622:            }
1.104     www      9623:         }
1.21      www      9624:         $mrole='cr';
1.678     raeburn  9625:     } elsif ($role =~ /^gr\//) {
                   9626:         my $cwogrp=$url;
1.811     albertel 9627:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9628:         unless (&allowed('mdg',$cwogrp)) {
                   9629:             &logthis('Refused group assignrole: '.
                   9630:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9631:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9632:             return 'refused';
                   9633:         }
                   9634:         $mrole='gr';
1.21      www      9635:     } else {
1.82      www      9636:         my $cwosec=$url;
1.811     albertel 9637:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9638:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9639:             my $refused;
                   9640:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9641:                 if (!(&allowed('c'.$role,$url))) {
                   9642:                     $refused = 1;
                   9643:                 }
                   9644:             } else {
                   9645:                 $refused = 1;
                   9646:             }
1.947     raeburn  9647:             if ($refused) {
1.1045    raeburn  9648:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9649:                 if (!$selfenroll && $context eq 'course') {
                   9650:                     my %crsenv;
                   9651:                     if ($role eq 'cc' || $role eq 'co') {
                   9652:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9653:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9654:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9655:                                 if ($crsenv{'internal.courseowner'} eq 
                   9656:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9657:                                     $refused = '';
                   9658:                                 }
                   9659:                             }
                   9660:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9661:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9662:                                 if ($crsenv{'internal.courseowner'} eq 
                   9663:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9664:                                     $refused = '';
                   9665:                                 }
                   9666:                             }
                   9667:                         }
                   9668:                     }
                   9669:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9670:                     $refused = '';
1.1017    raeburn  9671:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9672:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9673:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9674:                         my $wrongcc;
                   9675:                         if ($cnum =~ /^$match_community$/) {
                   9676:                             $wrongcc = 1 if ($role eq 'cc');
                   9677:                         } else {
                   9678:                             $wrongcc = 1 if ($role eq 'co');
                   9679:                         }
                   9680:                         unless ($wrongcc) {
                   9681:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9682:                             if ($crsenv{'internal.courseowner'} eq 
                   9683:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9684:                                 $refused = '';
                   9685:                             }
1.1017    raeburn  9686:                         }
                   9687:                     }
1.1172.2.9  raeburn  9688:                 } elsif ($context eq 'requestauthor') {
                   9689:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9690:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9691:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9692:                             $refused = '';
                   9693:                         } else {
                   9694:                             my %domdefaults = &get_domain_defaults($udom);
                   9695:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9696:                                 my $checkbystatus;
                   9697:                                 if ($env{'user.adv'}) {
                   9698:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9699:                                     if ($disposition eq 'automatic') {
                   9700:                                         $refused = '';
                   9701:                                     } elsif ($disposition eq '') {
                   9702:                                         $checkbystatus = 1;
                   9703:                                     }
                   9704:                                 } else {
                   9705:                                     $checkbystatus = 1;
                   9706:                                 }
                   9707:                                 if ($checkbystatus) {
                   9708:                                     if ($env{'environment.inststatus'}) {
                   9709:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9710:                                         foreach my $type (@inststatuses) {
                   9711:                                             if (($type ne '') &&
                   9712:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9713:                                                 $refused = '';
                   9714:                                             }
                   9715:                                         }
                   9716:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9717:                                         $refused = '';
                   9718:                                     }
                   9719:                                 }
                   9720:                             }
                   9721:                         }
                   9722:                     }
1.1017    raeburn  9723:                 }
                   9724:                 if ($refused) {
1.947     raeburn  9725:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9726:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9727: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9728:                     return 'refused';
                   9729:                 }
1.932     raeburn  9730:             }
1.1131    raeburn  9731:         } elsif ($role eq 'au') {
                   9732:             if ($url ne '/'.$udom.'/') {
                   9733:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9734:                          ' to assign author role for '.$uname.':'.$udom.
                   9735:                          ' in domain: '.$url.' refused (wrong domain).');
                   9736:                 return 'refused';
                   9737:             }
1.104     www      9738:         }
1.21      www      9739:         $mrole=$role;
                   9740:     }
1.620     albertel 9741:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9742:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9743:     if ($end) { $command.='_'.$end; }
1.21      www      9744:     if ($start) {
                   9745: 	if ($end) { 
1.81      www      9746:            $command.='_'.$start; 
1.21      www      9747:         } else {
1.81      www      9748:            $command.='_0_'.$start;
1.21      www      9749:         }
                   9750:     }
1.739     raeburn  9751:     my $origstart = $start;
                   9752:     my $origend = $end;
1.957     raeburn  9753:     my $delflag;
1.357     www      9754: # actually delete
                   9755:     if ($deleteflag) {
1.373     www      9756: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9757: # modify command to delete the role
1.620     albertel 9758:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9759:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9760: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9761: # set start and finish to negative values for userrolelog
                   9762:            $start=-1;
                   9763:            $end=-1;
1.957     raeburn  9764:            $delflag = 1;
1.357     www      9765:         }
                   9766:     }
                   9767: # send command
1.349     www      9768:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9769: # log new user role if status is ok
1.349     www      9770:     if ($answer eq 'ok') {
1.663     raeburn  9771: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9772:         if (($role eq 'cc') || ($role eq 'in') ||
                   9773:             ($role eq 'ep') || ($role eq 'ad') ||
                   9774:             ($role eq 'ta') || ($role eq 'st') ||
                   9775:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9776:             ($role eq 'co')) {
1.1172.2.13  raeburn  9777: # for course roles, perform group memberships changes triggered by role change.
                   9778:             unless ($role =~ /^gr/) {
                   9779:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9780:                                                  $origstart,$selfenroll,$context);
                   9781:             }
1.1172.2.9  raeburn  9782:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9783:                            $selfenroll,$context);
                   9784:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9785:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9786:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9787:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9788:                            $context);
                   9789:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9790:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9791:                              $context);
                   9792:         }
1.1053    raeburn  9793:         if ($role eq 'cc') {
                   9794:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9795:         }
1.349     www      9796:     }
                   9797:     return $answer;
1.169     harris41 9798: }
                   9799: 
1.1053    raeburn  9800: sub autoupdate_coowners {
                   9801:     my ($url,$end,$start,$uname,$udom) = @_;
                   9802:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9803:     if (($cdom ne '') && ($cnum ne '')) {
                   9804:         my $now = time;
                   9805:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9806:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9807:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9808:             my $instcode = $coursehash{'internal.coursecode'};
                   9809:             if ($instcode ne '') {
1.1056    raeburn  9810:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9811:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9812:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9813:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9814:                         if ($result eq 'valid') {
                   9815:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9816:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9817:                                     push(@newcoowners,$coowner);
                   9818:                                 }
                   9819:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9820:                                     push(@newcoowners,$uname.':'.$udom);
                   9821:                                 }
                   9822:                                 @newcoowners = sort(@newcoowners);
                   9823:                             } else {
                   9824:                                 push(@newcoowners,$uname.':'.$udom);
                   9825:                             }
                   9826:                         } else {
                   9827:                             if ($coursehash{'internal.co-owners'}) {
                   9828:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9829:                                     unless ($coowner eq $uname.':'.$udom) {
                   9830:                                         push(@newcoowners,$coowner);
                   9831:                                     }
                   9832:                                 }
                   9833:                                 unless (@newcoowners > 0) {
                   9834:                                     $delcoowners = 1;
                   9835:                                     $coowners = '';
                   9836:                                 }
                   9837:                             }
                   9838:                         }
                   9839:                         if (@newcoowners || $delcoowners) {
                   9840:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9841:                                             $delcoowners,@newcoowners);
                   9842:                         }
                   9843:                     }
                   9844:                 }
                   9845:             }
                   9846:         }
                   9847:     }
                   9848: }
                   9849: 
                   9850: sub store_coowners {
                   9851:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9852:     my $cid = $cdom.'_'.$cnum;
                   9853:     my ($coowners,$delresult,$putresult);
                   9854:     if (@newcoowners) {
                   9855:         $coowners = join(',',@newcoowners);
                   9856:         my %coownershash = (
                   9857:                             'internal.co-owners' => $coowners,
                   9858:                            );
                   9859:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9860:         if ($putresult eq 'ok') {
                   9861:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9862:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9863:             }
                   9864:         }
                   9865:     }
                   9866:     if ($delcoowners) {
                   9867:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9868:         if ($delresult eq 'ok') {
                   9869:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9870:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9871:             }
                   9872:         }
                   9873:     }
                   9874:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9875:         my %crsinfo =
                   9876:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9877:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9878:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9879:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9880:         }
                   9881:     }
                   9882: }
                   9883: 
1.169     harris41 9884: # -------------------------------------------------- Modify user authentication
1.197     www      9885: # Overrides without validation
                   9886: 
1.169     harris41 9887: sub modifyuserauth {
                   9888:     my ($udom,$uname,$umode,$upass)=@_;
                   9889:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9890:     my $allowed;
                   9891:     if (&allowed('mau',$udom)) {
                   9892:         $allowed = 1;
                   9893:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9894:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9895:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9896:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9897:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9898:         if (($cdom ne '') && ($cnum ne '')) {
                   9899:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9900:             if ($is_owner) {
                   9901:                 $allowed = 1;
                   9902:             }
                   9903:         }
                   9904:     }
                   9905:     unless ($allowed) { return 'refused'; }
1.197     www      9906:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9907:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9908:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9909:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9910: 		     &escape($upass),$uhome);
1.620     albertel 9911:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9912:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9913:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9914:     &log($udom,,$uname,$uhome,
1.620     albertel 9915:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9916:                                      $env{'user.name'}.', '.$umode.
1.197     www      9917:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9918:     unless ($reply eq 'ok') {
1.197     www      9919:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9920: 	return 'error: '.$reply;
                   9921:     }   
1.170     harris41 9922:     return 'ok';
1.80      www      9923: }
                   9924: 
1.81      www      9925: # --------------------------------------------------------------- Modify a user
1.80      www      9926: 
1.81      www      9927: sub modifyuser {
1.206     matthew  9928:     my ($udom,    $uname, $uid,
                   9929:         $umode,   $upass, $first,
                   9930:         $middle,  $last,  $gene,
1.1058    raeburn  9931:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9932:     $udom= &LONCAPA::clean_domain($udom);
                   9933:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9934:     my $showcandelete = 'none';
                   9935:     if (ref($candelete) eq 'ARRAY') {
                   9936:         if (@{$candelete} > 0) {
                   9937:             $showcandelete = join(', ',@{$candelete});
                   9938:         }
                   9939:     }
1.81      www      9940:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9941:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9942: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9943:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9944:                                      ' desiredhome not specified'). 
1.620     albertel 9945:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9946:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9947:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9948:     my $newuser;
                   9949:     if ($uhome eq 'no_host') {
                   9950:         $newuser = 1;
                   9951:     }
1.80      www      9952: # ----------------------------------------------------------------- Create User
1.406     albertel 9953:     if (($uhome eq 'no_host') && 
                   9954: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9955:         my $unhome='';
1.844     albertel 9956:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9957:             $unhome = $desiredhome;
1.620     albertel 9958: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9959: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9960:         } else { # load balancing routine for determining $unhome
1.81      www      9961:             my $loadm=10000000;
1.841     albertel 9962: 	    my %servers = &get_servers($udom,'library');
                   9963: 	    foreach my $tryserver (keys(%servers)) {
                   9964: 		my $answer=reply('load',$tryserver);
                   9965: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9966: 		    $loadm=$answer;
                   9967: 		    $unhome=$tryserver;
                   9968: 		}
1.80      www      9969: 	    }
                   9970:         }
                   9971:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9972: 	    return 'error: unable to find a home server for '.$uname.
                   9973:                    ' in domain '.$udom;
1.80      www      9974:         }
                   9975:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9976:                          &escape($upass),$unhome);
                   9977: 	unless ($reply eq 'ok') {
                   9978:             return 'error: '.$reply;
                   9979:         }   
1.230     stredwic 9980:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9981:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9982: 	    return 'error: unable verify users home machine.';
1.80      www      9983:         }
1.209     matthew  9984:     }   # End of creation of new user
1.80      www      9985: # ---------------------------------------------------------------------- Add ID
                   9986:     if ($uid) {
                   9987:        $uid=~tr/A-Z/a-z/;
                   9988:        my %uidhash=&idrget($udom,$uname);
1.196     www      9989:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9990:          && (!$forceid)) {
1.80      www      9991: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9992: 	      return 'error: user id "'.$uid.'" does not match '.
                   9993:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9994:           }
                   9995:        } else {
                   9996: 	  &idput($udom,($uname => $uid));
                   9997:        }
                   9998:     }
                   9999: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10000:     my @tmp=&get('environment',
1.899     raeburn  10001: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10002:                     'permanentemail','inststatus'],
1.134     albertel 10003: 		   $udom,$uname);
1.1075    raeburn  10004:     my (%names,%oldnames);
1.313     matthew  10005:     if ($tmp[0] =~ m/^error:.*/) { 
                   10006:         %names=(); 
                   10007:     } else {
                   10008:         %names = @tmp;
1.1075    raeburn  10009:         %oldnames = %names;
1.313     matthew  10010:     }
1.388     www      10011: #
1.1058    raeburn  10012: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10013: # of users did not contain them), do not overwrite existing values
                   10014: # unless field is in $candelete array ref.  
                   10015: #
                   10016: 
                   10017:     my @fields = ('firstname','middlename','lastname','generation',
                   10018:                   'permanentemail','id');
                   10019:     my %newvalues;
                   10020:     if (ref($candelete) eq 'ARRAY') {
                   10021:         foreach my $field (@fields) {
                   10022:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10023:                 if ($field eq 'firstname') {
                   10024:                     $names{$field} = $first;
                   10025:                 } elsif ($field eq 'middlename') {
                   10026:                     $names{$field} = $middle;
                   10027:                 } elsif ($field eq 'lastname') {
                   10028:                     $names{$field} = $last;
                   10029:                 } elsif ($field eq 'generation') { 
                   10030:                     $names{$field} = $gene;
                   10031:                 } elsif ($field eq 'permanentemail') {
                   10032:                     $names{$field} = $email;
                   10033:                 } elsif ($field eq 'id') {
                   10034:                     $names{$field}  = $uid;
                   10035:                 }
                   10036:             }
                   10037:         }
                   10038:     }
1.388     www      10039:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10040:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10041:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10042:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10043:     if ($email) {
                   10044:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10045:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10046:     }
1.899     raeburn  10047:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10048:     if (defined($inststatus)) {
                   10049:         $names{'inststatus'} = '';
                   10050:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10051:         if (ref($usertypes) eq 'HASH') {
                   10052:             my @okstatuses; 
                   10053:             foreach my $item (split(/:/,$inststatus)) {
                   10054:                 if (defined($usertypes->{$item})) {
                   10055:                     push(@okstatuses,$item);  
                   10056:                 }
                   10057:             }
                   10058:             if (@okstatuses) {
                   10059:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10060:             }
                   10061:         }
                   10062:     }
1.1075    raeburn  10063:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10064:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10065:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10066:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10067:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10068:     } else {
                   10069:         $logmsg .= ' during self creation';
                   10070:     }
1.1075    raeburn  10071:     my $changed;
                   10072:     if ($newuser) {
                   10073:         $changed = 1;
                   10074:     } else {
                   10075:         foreach my $field (@fields) {
                   10076:             if ($names{$field} ne $oldnames{$field}) {
                   10077:                 $changed = 1;
                   10078:                 last;
                   10079:             }
                   10080:         }
                   10081:     }
                   10082:     unless ($changed) {
                   10083:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10084:         &logthis($logmsg);
                   10085:         return 'ok';
                   10086:     }
                   10087:     my $reply = &put('environment', \%names, $udom,$uname);
                   10088:     if ($reply ne 'ok') { 
                   10089:         return 'error: '.$reply;
                   10090:     }
1.1087    raeburn  10091:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10092:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10093:     }
1.1075    raeburn  10094:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10095:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10096:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10097:     &logthis($logmsg);
1.134     albertel 10098:     return 'ok';
1.80      www      10099: }
                   10100: 
1.81      www      10101: # -------------------------------------------------------------- Modify student
1.80      www      10102: 
1.81      www      10103: sub modifystudent {
                   10104:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10105:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10106:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10107:     if (!$cid) {
1.620     albertel 10108: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10109: 	    return 'not_in_class';
                   10110: 	}
1.80      www      10111:     }
                   10112: # --------------------------------------------------------------- Make the user
1.81      www      10113:     my $reply=&modifyuser
1.209     matthew  10114: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10115:          $desiredhome,$email,$inststatus);
1.80      www      10116:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10117:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10118:     # student's environment
1.297     matthew  10119:     $uid = undef if (!$forceid);
1.455     albertel 10120:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10121: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10122:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10123:     return $reply;
                   10124: }
                   10125: 
                   10126: sub modify_student_enrollment {
1.1172.2.23  raeburn  10127:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10128:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10129:     my ($cdom,$cnum,$chome);
                   10130:     if (!$cid) {
1.620     albertel 10131: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10132: 	    return 'not_in_class';
                   10133: 	}
1.620     albertel 10134: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10135: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10136:     } else {
                   10137: 	($cdom,$cnum)=split(/_/,$cid);
                   10138:     }
1.620     albertel 10139:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10140:     if (!$chome) {
1.457     raeburn  10141: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10142:     }
1.455     albertel 10143:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10144:     # Make sure the user exists
1.81      www      10145:     my $uhome=&homeserver($uname,$udom);
                   10146:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10147: 	return 'error: no such user';
                   10148:     }
1.297     matthew  10149:     # Get student data if we were not given enough information
                   10150:     if (!defined($first)  || $first  eq '' || 
                   10151:         !defined($last)   || $last   eq '' || 
                   10152:         !defined($uid)    || $uid    eq '' || 
                   10153:         !defined($middle) || $middle eq '' || 
                   10154:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10155:         # They did not supply us with enough data to enroll the student, so
                   10156:         # we need to pick up more information.
1.297     matthew  10157:         my %tmp = &get('environment',
1.294     matthew  10158:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10159:                        ,$udom,$uname);
                   10160: 
1.800     albertel 10161:         #foreach my $key (keys(%tmp)) {
                   10162:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10163:         #}
1.294     matthew  10164:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10165:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10166:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10167:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10168:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10169:     }
1.556     albertel 10170:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10171:     my $user = "$uname:$udom";
                   10172:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10173:     my $reply=cput('classlist',
1.1148    raeburn  10174: 		   {$user => 
1.1172.2.76  raeburn  10175: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10176: 		   $cdom,$cnum);
1.1148    raeburn  10177:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10178:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10179:     } else { 
1.81      www      10180: 	return 'error: '.$reply;
                   10181:     }
1.297     matthew  10182:     # Add student role to user
1.83      www      10183:     my $uurl='/'.$cid;
1.81      www      10184:     $uurl=~s/\_/\//g;
                   10185:     if ($usec) {
                   10186: 	$uurl.='/'.$usec;
                   10187:     }
1.1148    raeburn  10188:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10189:                              $selfenroll,$context);
                   10190:     if ($result ne 'ok') {
                   10191:         if ($old_entry{$user} ne '') {
                   10192:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10193:         } else {
                   10194:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10195:         }
                   10196:     }
                   10197:     return $result; 
1.21      www      10198: }
                   10199: 
1.556     albertel 10200: sub format_name {
                   10201:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10202:     my $name;
                   10203:     if ($first ne 'lastname') {
                   10204: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10205:     } else {
                   10206: 	if ($lastname=~/\S/) {
                   10207: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10208: 	    $name=~s/\s+,/,/;
                   10209: 	} else {
                   10210: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10211: 	}
                   10212:     }
                   10213:     $name=~s/^\s+//;
                   10214:     $name=~s/\s+$//;
                   10215:     $name=~s/\s+/ /g;
                   10216:     return $name;
                   10217: }
                   10218: 
1.84      www      10219: # ------------------------------------------------- Write to course preferences
                   10220: 
                   10221: sub writecoursepref {
                   10222:     my ($courseid,%prefs)=@_;
                   10223:     $courseid=~s/^\///;
                   10224:     $courseid=~s/\_/\//g;
                   10225:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10226:     my $chome=homeserver($cnum,$cdomain);
                   10227:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10228: 	return 'error: no such course';
                   10229:     }
                   10230:     my $cstring='';
1.800     albertel 10231:     foreach my $pref (keys(%prefs)) {
                   10232: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10233:     }
1.84      www      10234:     $cstring=~s/\&$//;
                   10235:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10236: }
                   10237: 
                   10238: # ---------------------------------------------------------- Make/modify course
                   10239: 
                   10240: sub createcourse {
1.741     raeburn  10241:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10242:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10243:     $url=&declutter($url);
                   10244:     my $cid='';
1.1028    raeburn  10245:     if ($context eq 'requestcourses') {
                   10246:         my $can_create = 0;
                   10247:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10248:         if ($udom eq $ownerdom) {
                   10249:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10250:                                   $context)) {
                   10251:                 $can_create = 1;
                   10252:             }
                   10253:         } else {
                   10254:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10255:                                            $category);
                   10256:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10257:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10258:                 if (@curr > 0) {
                   10259:                     my @options = qw(approval validate autolimit);
                   10260:                     my $optregex = join('|',@options);
                   10261:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10262:                         $can_create = 1;
                   10263:                     }
                   10264:                 }
                   10265:             }
                   10266:         }
                   10267:         if ($can_create) {
                   10268:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10269:                 unless (&allowed('ccc',$udom)) {
                   10270:                     return 'refused'; 
                   10271:                 }
1.1017    raeburn  10272:             }
                   10273:         } else {
                   10274:             return 'refused';
                   10275:         }
1.1028    raeburn  10276:     } elsif (!&allowed('ccc',$udom)) {
                   10277:         return 'refused';
1.84      www      10278:     }
1.1011    raeburn  10279: # --------------------------------------------------------------- Get Unique ID
                   10280:     my $uname;
                   10281:     if ($cnum =~ /^$match_courseid$/) {
                   10282:         my $chome=&homeserver($cnum,$udom,'true');
                   10283:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10284:             $uname = $cnum;
                   10285:         } else {
1.1038    raeburn  10286:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10287:         }
                   10288:     } else {
1.1038    raeburn  10289:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10290:     }
                   10291:     return $uname if ($uname =~ /^error/);
                   10292: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10293:     if (!defined($course_server)) {
                   10294:         if (defined(&domain($udom,'primary'))) {
                   10295:             $course_server = &domain($udom,'primary');
                   10296:         } else {
                   10297:             $course_server = $env{'user.home'}; 
                   10298:         }
                   10299:     }
                   10300:     my %host_servers =
                   10301:         &Apache::lonnet::get_servers($udom,'library');
                   10302:     unless ($host_servers{$course_server}) {
                   10303:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10304:     }
1.84      www      10305: # ------------------------------------------------------------- Make the course
                   10306:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10307:                       $course_server);
1.84      www      10308:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10309:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10310:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10311: 	return 'error: no such course';
                   10312:     }
1.271     www      10313: # ----------------------------------------------------------------- Course made
1.516     raeburn  10314: # log existence
1.1029    raeburn  10315:     my $now = time;
1.918     raeburn  10316:     my $newcourse = {
                   10317:                     $udom.'_'.$uname => {
1.921     raeburn  10318:                                      description => $description,
                   10319:                                      inst_code   => $inst_code,
                   10320:                                      owner       => $course_owner,
                   10321:                                      type        => $crstype,
1.1029    raeburn  10322:                                      creator     => $env{'user.name'}.':'.
                   10323:                                                     $env{'user.domain'},
                   10324:                                      created     => $now,
                   10325:                                      context     => $context,
1.918     raeburn  10326:                                                 },
                   10327:                     };
1.921     raeburn  10328:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10329: # set toplevel url
1.271     www      10330:     my $topurl=$url;
                   10331:     unless ($nonstandard) {
                   10332: # ------------------------------------------ For standard courses, make top url
                   10333:         my $mapurl=&clutter($url);
1.278     www      10334:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10335:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10336: <map>
                   10337: <resource id="1" type="start"></resource>
                   10338: <resource id="2" src="$mapurl"></resource>
                   10339: <resource id="3" type="finish"></resource>
                   10340: <link index="1" from="1" to="2"></link>
                   10341: <link index="2" from="2" to="3"></link>
                   10342: </map>
                   10343: ENDINITMAP
                   10344:         $topurl=&declutter(
1.638     albertel 10345:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10346:                           );
                   10347:     }
                   10348: # ----------------------------------------------------------- Write preferences
1.84      www      10349:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10350:                      ('description'              => $description,
                   10351:                       'url'                      => $topurl,
                   10352:                       'internal.creator'         => $env{'user.name'}.':'.
                   10353:                                                     $env{'user.domain'},
                   10354:                       'internal.created'         => $now,
                   10355:                       'internal.creationcontext' => $context)
                   10356:                     );
1.84      www      10357:     return '/'.$udom.'/'.$uname;
                   10358: }
                   10359: 
1.1011    raeburn  10360: # ------------------------------------------------------------------- Create ID
                   10361: sub generate_coursenum {
1.1038    raeburn  10362:     my ($udom,$crstype) = @_;
1.1011    raeburn  10363:     my $domdesc = &domain($udom);
                   10364:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10365:     my $first;
                   10366:     if ($crstype eq 'Community') {
                   10367:         $first = '0';
                   10368:     } else {
                   10369:         $first = int(1+rand(9)); 
                   10370:     } 
                   10371:     my $uname=$first.
1.1011    raeburn  10372:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10373:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10374:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10375: # ----------------------------------------------- Make sure that does not exist
                   10376:     my $uhome=&homeserver($uname,$udom,'true');
                   10377:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10378:         if ($crstype eq 'Community') {
                   10379:             $first = '0';
                   10380:         } else {
                   10381:             $first = int(1+rand(9));
                   10382:         }
                   10383:         $uname=$first.
1.1011    raeburn  10384:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10385:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10386:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10387:         $uhome=&homeserver($uname,$udom,'true');
                   10388:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10389:             return 'error: unable to generate unique course-ID';
                   10390:         }
                   10391:     }
                   10392:     return $uname;
                   10393: }
                   10394: 
1.813     albertel 10395: sub is_course {
1.1167    droeschl 10396:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10397:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10398:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10399:     my $uhome=&homeserver($cnum,$cdom);
                   10400:     my $iscourse;
                   10401:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10402:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10403:     } else {
                   10404:         my $hashid = $cdom.':'.$cnum;
                   10405:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10406:         unless (defined($cached)) {
                   10407:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10408:                                         $cnum,undef,undef,'.');
                   10409:             $iscourse = 0;
                   10410:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10411:                 $iscourse = 1;
                   10412:             }
                   10413:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10414:         }
                   10415:     }
                   10416:     return unless($iscourse);
1.1167    droeschl 10417:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10418: }
                   10419: 
1.1015    raeburn  10420: sub store_userdata {
                   10421:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10422:     my $result;
1.1016    raeburn  10423:     if ($datakey ne '') {
1.1013    raeburn  10424:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10425:             if ($udom eq '' || $uname eq '') {
                   10426:                 $udom = $env{'user.domain'};
                   10427:                 $uname = $env{'user.name'};
                   10428:             }
                   10429:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10430:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10431:                 $result = 'error: no_host';
                   10432:             } else {
                   10433:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10434:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10435: 
                   10436:                 my $namevalue='';
                   10437:                 foreach my $key (keys(%{$storehash})) {
                   10438:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10439:                 }
                   10440:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10441:                 unless ($namespace eq 'courserequests') {
                   10442:                     $datakey = &escape($datakey);
                   10443:                 }
1.1105    raeburn  10444:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10445:                                   $namevalue,$uhome);
1.1013    raeburn  10446:             }
                   10447:         } else {
                   10448:             $result = 'error: data to store was not a hash reference'; 
                   10449:         }
                   10450:     } else {
                   10451:         $result= 'error: invalid requestkey'; 
                   10452:     }
                   10453:     return $result;
                   10454: }
                   10455: 
1.21      www      10456: # ---------------------------------------------------------- Assign Custom Role
                   10457: 
                   10458: sub assigncustomrole {
1.957     raeburn  10459:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10460:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10461:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10462: }
                   10463: 
                   10464: # ----------------------------------------------------------------- Revoke Role
                   10465: 
                   10466: sub revokerole {
1.957     raeburn  10467:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10468:     my $now=time;
1.965     raeburn  10469:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10470: }
                   10471: 
                   10472: # ---------------------------------------------------------- Revoke Custom Role
                   10473: 
                   10474: sub revokecustomrole {
1.957     raeburn  10475:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10476:     my $now=time;
1.357     www      10477:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10478:            $deleteflag,$selfenroll,$context);
1.17      www      10479: }
                   10480: 
1.533     banghart 10481: # ------------------------------------------------------------ Disk usage
1.535     albertel 10482: sub diskusage {
1.955     raeburn  10483:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10484:     $directorypath =~ s/\/$//;
                   10485:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10486:                        .&escape($getpropath).':'.&escape($uname).':'
                   10487:                        .&escape($udom),homeserver($uname,$udom));
                   10488:     if ($listing eq 'unknown_cmd') {
                   10489:         if ($getpropath) {
                   10490:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10491:         }
                   10492:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10493:     }
1.514     albertel 10494:     return $listing;
1.512     banghart 10495: }
                   10496: 
1.566     banghart 10497: sub is_locked {
1.1096    raeburn  10498:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10499:     my @check;
                   10500:     my $is_locked;
1.1093    raeburn  10501:     push (@check,$file_name);
1.613     albertel 10502:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10503: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10504:     my ($tmp)=keys(%locked);
                   10505:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10506:     
1.566     banghart 10507:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10508:         $is_locked = 'false';
                   10509:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10510:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10511:                $is_locked = 'true';
1.1096    raeburn  10512:                if (ref($which) eq 'ARRAY') {
                   10513:                    push(@{$which},$entry);
                   10514:                } else {
                   10515:                    last;
                   10516:                }
1.745     raeburn  10517:            }
                   10518:        }
1.566     banghart 10519:     } else {
                   10520:         $is_locked = 'false';
                   10521:     }
1.1093    raeburn  10522:     return $is_locked;
1.566     banghart 10523: }
                   10524: 
1.759     albertel 10525: sub declutter_portfile {
                   10526:     my ($file) = @_;
1.833     albertel 10527:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10528:     return $file;
                   10529: }
                   10530: 
1.559     banghart 10531: # ------------------------------------------------------------- Mark as Read Only
                   10532: 
                   10533: sub mark_as_readonly {
                   10534:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10535:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10536:     my ($tmp)=keys(%current_permissions);
                   10537:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10538:     foreach my $file (@{$files}) {
1.759     albertel 10539: 	$file = &declutter_portfile($file);
1.561     banghart 10540:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10541:     }
1.613     albertel 10542:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10543:     return;
                   10544: }
                   10545: 
1.572     banghart 10546: # ------------------------------------------------------------Save Selected Files
                   10547: 
                   10548: sub save_selected_files {
                   10549:     my ($user, $path, @files) = @_;
                   10550:     my $filename = $user."savedfiles";
1.573     banghart 10551:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10552:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10553:     foreach my $file (@files) {
1.620     albertel 10554:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10555:     }
                   10556:     foreach my $file (@other_files) {
1.574     banghart 10557:         print (OUT $file."\n");
1.572     banghart 10558:     }
1.574     banghart 10559:     close (OUT);
1.572     banghart 10560:     return 'ok';
                   10561: }
                   10562: 
1.574     banghart 10563: sub clear_selected_files {
                   10564:     my ($user) = @_;
                   10565:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10566:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10567:     print (OUT undef);
                   10568:     close (OUT);
                   10569:     return ("ok");    
                   10570: }
                   10571: 
1.572     banghart 10572: sub files_in_path {
                   10573:     my ($user, $path) = @_;
                   10574:     my $filename = $user."savedfiles";
                   10575:     my %return_files;
1.1172.2.96  raeburn  10576:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10577:     while (my $line_in = <IN>) {
1.574     banghart 10578:         chomp ($line_in);
                   10579:         my @paths_and_file = split (m!/!, $line_in);
                   10580:         my $file_part = pop (@paths_and_file);
                   10581:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10582:         $path_part.='/';
                   10583:         my $path_and_file = $path_part.$file_part;
                   10584:         if ($path_part eq $path) {
                   10585:             $return_files{$file_part}= 'selected';
                   10586:         }
                   10587:     }
1.574     banghart 10588:     close (IN);
                   10589:     return (\%return_files);
1.572     banghart 10590: }
                   10591: 
                   10592: # called in portfolio select mode, to show files selected NOT in current directory
                   10593: sub files_not_in_path {
                   10594:     my ($user, $path) = @_;
                   10595:     my $filename = $user."savedfiles";
                   10596:     my @return_files;
                   10597:     my $path_part;
1.1172.2.96  raeburn  10598:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10599:     while (my $line = <IN>) {
1.572     banghart 10600:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10601:         my @paths_and_file = split(m|/|, $line);
                   10602:         my $file_part = pop(@paths_and_file);
                   10603:         chomp($file_part);
                   10604:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10605:         $path_part .= '/';
                   10606:         my $path_and_file = $path_part.$file_part;
                   10607:         if ($path_part ne $path) {
1.800     albertel 10608:             push(@return_files, ($path_and_file));
1.572     banghart 10609:         }
                   10610:     }
1.800     albertel 10611:     close(OUT);
1.574     banghart 10612:     return (@return_files);
1.572     banghart 10613: }
                   10614: 
1.745     raeburn  10615: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10616: 
1.745     raeburn  10617: sub get_portfile_permissions {
                   10618:     my ($domain,$user) = @_;
1.613     albertel 10619:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10620:     my ($tmp)=keys(%current_permissions);
                   10621:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10622:     return \%current_permissions;
                   10623: }
                   10624: 
                   10625: #---------------------------------------------Get portfolio file access controls
                   10626: 
1.749     raeburn  10627: sub get_access_controls {
1.745     raeburn  10628:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10629:     my %access;
                   10630:     my $real_file = $file;
                   10631:     $file =~ s/\.meta$//;
1.745     raeburn  10632:     if (defined($file)) {
1.749     raeburn  10633:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10634:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10635:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10636:             }
                   10637:         }
1.745     raeburn  10638:     } else {
1.749     raeburn  10639:         foreach my $key (keys(%{$current_permissions})) {
                   10640:             if ($key =~ /\0accesscontrol$/) {
                   10641:                 if (defined($group)) {
                   10642:                     if ($key !~ m-^\Q$group\E/-) {
                   10643:                         next;
                   10644:                     }
                   10645:                 }
                   10646:                 my ($fullpath) = split(/\0/,$key);
                   10647:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10648:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10649:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10650:                     }
                   10651:                 }
                   10652:             }
                   10653:         }
                   10654:     }
                   10655:     return %access;
                   10656: }
                   10657: 
                   10658: sub modify_access_controls {
                   10659:     my ($file_name,$changes,$domain,$user)=@_;
                   10660:     my ($outcome,$deloutcome);
                   10661:     my %store_permissions;
                   10662:     my %new_values;
                   10663:     my %new_control;
                   10664:     my %translation;
                   10665:     my @deletions = ();
                   10666:     my $now = time;
                   10667:     if (exists($$changes{'activate'})) {
                   10668:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10669:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10670:             my $numnew = scalar(@newitems);
                   10671:             for (my $i=0; $i<$numnew; $i++) {
                   10672:                 my $newkey = $newitems[$i];
                   10673:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10674:                 if ($newkey =~ /^\d+:/) { 
                   10675:                     $newkey =~ s/^(\d+)/$newid/;
                   10676:                     $translation{$1} = $newid;
                   10677:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10678:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10679:                     $translation{$1} = $newid;
                   10680:                 }
1.749     raeburn  10681:                 $new_values{$file_name."\0".$newkey} = 
                   10682:                                           $$changes{'activate'}{$newitems[$i]};
                   10683:                 $new_control{$newkey} = $now;
                   10684:             }
                   10685:         }
                   10686:     }
                   10687:     my %todelete;
                   10688:     my %changed_items;
                   10689:     foreach my $action ('delete','update') {
                   10690:         if (exists($$changes{$action})) {
                   10691:             if (ref($$changes{$action}) eq 'HASH') {
                   10692:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10693:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10694:                     if ($action eq 'delete') { 
                   10695:                         $todelete{$itemnum} = 1;
                   10696:                     } else {
                   10697:                         $changed_items{$itemnum} = $key;
                   10698:                     }
                   10699:                 }
1.745     raeburn  10700:             }
                   10701:         }
1.749     raeburn  10702:     }
                   10703:     # get lock on access controls for file.
                   10704:     my $lockhash = {
                   10705:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10706:                                                        ':'.$env{'user.domain'},
                   10707:                    }; 
                   10708:     my $tries = 0;
                   10709:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10710:    
1.1172.2.79  raeburn  10711:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10712:         $tries ++;
1.1172.2.79  raeburn  10713:         sleep(0.1);
1.749     raeburn  10714:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10715:     }
                   10716:     if ($gotlock eq 'ok') {
                   10717:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10718:         my ($tmp)=keys(%curr_permissions);
                   10719:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10720:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10721:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10722:             if (ref($curr_controls) eq 'HASH') {
                   10723:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10724:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10725:                     if (defined($todelete{$itemnum})) {
                   10726:                         push(@deletions,$file_name."\0".$control_item);
                   10727:                     } else {
                   10728:                         if (defined($changed_items{$itemnum})) {
                   10729:                             $new_control{$changed_items{$itemnum}} = $now;
                   10730:                             push(@deletions,$file_name."\0".$control_item);
                   10731:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10732:                         } else {
                   10733:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10734:                         }
                   10735:                     }
1.745     raeburn  10736:                 }
                   10737:             }
                   10738:         }
1.970     raeburn  10739:         my ($group);
                   10740:         if (&is_course($domain,$user)) {
                   10741:             ($group,my $file) = split(/\//,$file_name,2);
                   10742:         }
1.749     raeburn  10743:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10744:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10745:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10746:         #  remove lock
                   10747:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10748:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10749:         my $sqlresult =
1.970     raeburn  10750:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10751:                                     $group);
1.749     raeburn  10752:     } else {
                   10753:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10754:     }
1.749     raeburn  10755:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10756: }
                   10757: 
1.827     raeburn  10758: sub make_public_indefinitely {
                   10759:     my ($requrl) = @_;
                   10760:     my $now = time;
                   10761:     my $action = 'activate';
                   10762:     my $aclnum = 0;
                   10763:     if (&is_portfolio_url($requrl)) {
                   10764:         my (undef,$udom,$unum,$file_name,$group) =
                   10765:             &parse_portfolio_url($requrl);
                   10766:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10767:         my %access_controls = &get_access_controls($current_perms,
                   10768:                                                    $group,$file_name);
                   10769:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10770:             my ($num,$scope,$end,$start) = 
                   10771:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10772:             if ($scope eq 'public') {
                   10773:                 if ($start <= $now && $end == 0) {
                   10774:                     $action = 'none';
                   10775:                 } else {
                   10776:                     $action = 'update';
                   10777:                     $aclnum = $num;
                   10778:                 }
                   10779:                 last;
                   10780:             }
                   10781:         }
                   10782:         if ($action eq 'none') {
                   10783:              return 'ok';
                   10784:         } else {
                   10785:             my %changes;
                   10786:             my $newend = 0;
                   10787:             my $newstart = $now;
                   10788:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10789:             $changes{$action}{$newkey} = {
                   10790:                 type => 'public',
                   10791:                 time => {
                   10792:                     start => $newstart,
                   10793:                     end   => $newend,
                   10794:                 },
                   10795:             };
                   10796:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10797:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10798:             return $outcome;
                   10799:         }
                   10800:     } else {
                   10801:         return 'invalid';
                   10802:     }
                   10803: }
                   10804: 
1.745     raeburn  10805: #------------------------------------------------------Get Marked as Read Only
                   10806: 
                   10807: sub get_marked_as_readonly {
                   10808:     my ($domain,$user,$what,$group) = @_;
                   10809:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10810:     my @readonly_files;
1.629     banghart 10811:     my $cmp1=$what;
                   10812:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10813:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10814:         if (defined($group)) {
                   10815:             if ($file_name !~ m-^\Q$group\E/-) {
                   10816:                 next;
                   10817:             }
                   10818:         }
1.561     banghart 10819:         if (ref($value) eq "ARRAY"){
                   10820:             foreach my $stored_what (@{$value}) {
1.629     banghart 10821:                 my $cmp2=$stored_what;
1.759     albertel 10822:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10823:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10824:                 }
1.629     banghart 10825:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10826:                     push(@readonly_files, $file_name);
1.745     raeburn  10827:                     last;
1.563     banghart 10828:                 } elsif (!defined($what)) {
                   10829:                     push(@readonly_files, $file_name);
1.745     raeburn  10830:                     last;
1.561     banghart 10831:                 }
                   10832:             }
1.745     raeburn  10833:         }
1.561     banghart 10834:     }
                   10835:     return @readonly_files;
                   10836: }
1.577     banghart 10837: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10838: 
1.577     banghart 10839: sub get_marked_as_readonly_hash {
1.745     raeburn  10840:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10841:     my %readonly_files;
1.745     raeburn  10842:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10843:         if (defined($group)) {
                   10844:             if ($file_name !~ m-^\Q$group\E/-) {
                   10845:                 next;
                   10846:             }
                   10847:         }
1.577     banghart 10848:         if (ref($value) eq "ARRAY"){
                   10849:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10850:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10851:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10852:                         if ($lock_descriptor eq 'graded') {
                   10853:                             $readonly_files{$file_name} = 'graded';
                   10854:                         } elsif ($lock_descriptor eq 'handback') {
                   10855:                             $readonly_files{$file_name} = 'handback';
                   10856:                         } else {
                   10857:                             if (!exists($readonly_files{$file_name})) {
                   10858:                                 $readonly_files{$file_name} = 'locked';
                   10859:                             }
                   10860:                         }
1.745     raeburn  10861:                     }
1.750     banghart 10862:                 } 
1.577     banghart 10863:             }
                   10864:         } 
                   10865:     }
                   10866:     return %readonly_files;
                   10867: }
1.559     banghart 10868: # ------------------------------------------------------------ Unmark as Read Only
                   10869: 
                   10870: sub unmark_as_readonly {
1.629     banghart 10871:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10872:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10873:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10874:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10875:     my $symb_crs = $what;
                   10876:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10877:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10878:     my ($tmp)=keys(%current_permissions);
                   10879:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10880:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10881:     foreach my $file (@readonly_files) {
1.759     albertel 10882: 	my $clean_file = &declutter_portfile($file);
                   10883: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10884: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10885:         my @new_locks;
                   10886:         my @del_keys;
                   10887:         if (ref($current_locks) eq "ARRAY"){
                   10888:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10889:                 my $compare=$locker;
1.749     raeburn  10890:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10891:                     $compare=join('',@{$locker});
1.746     raeburn  10892:                     if ($compare ne $symb_crs) {
                   10893:                         push(@new_locks, $locker);
                   10894:                     }
1.563     banghart 10895:                 }
                   10896:             }
1.650     albertel 10897:             if (scalar(@new_locks) > 0) {
1.563     banghart 10898:                 $current_permissions{$file} = \@new_locks;
                   10899:             } else {
                   10900:                 push(@del_keys, $file);
1.613     albertel 10901:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10902:                 delete($current_permissions{$file});
1.563     banghart 10903:             }
                   10904:         }
1.561     banghart 10905:     }
1.613     albertel 10906:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10907:     return;
                   10908: }
1.512     banghart 10909: 
1.17      www      10910: # ------------------------------------------------------------ Directory lister
                   10911: 
                   10912: sub dirlist {
1.955     raeburn  10913:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10914:     $uri=~s/^\///;
                   10915:     $uri=~s/\/$//;
1.253     stredwic 10916:     my ($udom, $uname);
1.955     raeburn  10917:     if ($getuserdir) {
1.253     stredwic 10918:         $udom = $userdomain;
                   10919:         $uname = $username;
1.955     raeburn  10920:     } else {
                   10921:         (undef,$udom,$uname)=split(/\//,$uri);
                   10922:         if(defined($userdomain)) {
                   10923:             $udom = $userdomain;
                   10924:         }
                   10925:         if(defined($username)) {
                   10926:             $uname = $username;
                   10927:         }
1.253     stredwic 10928:     }
1.955     raeburn  10929:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10930: 
1.955     raeburn  10931:     $dirRoot = $perlvar{'lonDocRoot'};
                   10932:     if (defined($getpropath)) {
                   10933:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10934:         $dirRoot =~ s/\/$//;
1.955     raeburn  10935:     } elsif (defined($getuserdir)) {
                   10936:         my $subdir=$uname.'__';
                   10937:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10938:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10939:                    ."/$udom/$subdir/$uname";
                   10940:     } elsif (defined($alternateRoot)) {
                   10941:         $dirRoot = $alternateRoot;
1.751     banghart 10942:     }
1.253     stredwic 10943: 
                   10944:     if($udom) {
                   10945:         if($uname) {
1.1135    raeburn  10946:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10947:             if ($uhome eq 'no_host') {
                   10948:                 return ([],'no_host');
                   10949:             }
1.955     raeburn  10950:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10951:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10952:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10953:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10954:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10955:             } else {
                   10956:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10957:             }
1.605     matthew  10958:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10959:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10960:                 @listing_results = split(/:/,$listing);
                   10961:             } else {
                   10962:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10963:             }
1.1135    raeburn  10964:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10965:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10966:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10967:                 return ([],$listing);
                   10968:             } else {
                   10969:                 return (\@listing_results);
1.1135    raeburn  10970:             }
1.955     raeburn  10971:         } elsif(!$alternateRoot) {
1.1136    raeburn  10972:             my (%allusers,%listerror);
1.841     albertel 10973: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10974:  	    foreach my $tryserver (keys(%servers)) {
                   10975:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10976:                                   &escape($udom),$tryserver);
                   10977:                 if ($listing eq 'unknown_cmd') {
                   10978: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10979: 				      $udom, $tryserver);
                   10980:                 } else {
                   10981:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10982:                 }
1.841     albertel 10983: 		if ($listing eq 'unknown_cmd') {
                   10984: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10985: 				      $udom, $tryserver);
                   10986: 		    @listing_results = split(/:/,$listing);
                   10987: 		} else {
                   10988: 		    @listing_results =
                   10989: 			map { &unescape($_); } split(/:/,$listing);
                   10990: 		}
1.1136    raeburn  10991:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10992:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10993:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10994:                     $listerror{$tryserver} = $listing;
                   10995:                 } else {
1.841     albertel 10996: 		    foreach my $line (@listing_results) {
                   10997: 			my ($entry) = split(/&/,$line,2);
                   10998: 			$allusers{$entry} = 1;
                   10999: 		    }
                   11000: 		}
1.253     stredwic 11001:             }
1.1136    raeburn  11002:             my @alluserslist=();
1.800     albertel 11003:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11004:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11005:             }
1.1172.2.80  raeburn  11006:             if (!%listerror) {
                   11007:                 # no errors
                   11008:                 return (\@alluserslist);
                   11009:             } elsif (scalar(keys(%servers)) == 1) {
                   11010:                 # one library server, one error
                   11011:                 my ($key) = keys(%listerror);
                   11012:                 return (\@alluserslist, $listerror{$key});
                   11013:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11014:                 # con_lost indicates that we might miss data from at least one
                   11015:                 # library server
                   11016:                 return (\@alluserslist, 'con_lost');
                   11017:             } else {
                   11018:                 # multiple library servers and no con_lost -> data should be
                   11019:                 # complete.
                   11020:                 return (\@alluserslist);
                   11021:             }
                   11022: 
1.253     stredwic 11023:         } else {
1.1136    raeburn  11024:             return ([],'missing username');
1.253     stredwic 11025:         }
1.955     raeburn  11026:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11027:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11028:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11029:         return (\@all_domains);
1.955     raeburn  11030:     } else {
1.1136    raeburn  11031:         return ([],'missing domain');
1.275     stredwic 11032:     }
                   11033: }
                   11034: 
                   11035: # --------------------------------------------- GetFileTimestamp
                   11036: # This function utilizes dirlist and returns the date stamp for
                   11037: # when it was last modified.  It will also return an error of -1
                   11038: # if an error occurs
                   11039: 
                   11040: sub GetFileTimestamp {
1.955     raeburn  11041:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11042:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11043:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11044:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11045:                                     undef,$getuserdir);
                   11046:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11047:         return -1;
                   11048:     }
                   11049:     if (ref($fileref) eq 'ARRAY') {
                   11050:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11051:         # @stats contains first the filename, then the stat output
                   11052:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11053:     } else {
                   11054:         return -1;
1.253     stredwic 11055:     }
1.26      www      11056: }
                   11057: 
1.712     albertel 11058: sub stat_file {
                   11059:     my ($uri) = @_;
1.787     albertel 11060:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11061: 
1.955     raeburn  11062:     my ($udom,$uname,$file);
1.712     albertel 11063:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11064: 	($udom,$uname,$file) =
1.811     albertel 11065: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11066: 	$file = 'userfiles/'.$file;
                   11067:     }
                   11068:     if ($uri =~ m-^/res/-) {
                   11069: 	($udom,$uname) = 
1.807     albertel 11070: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11071: 	$file = $uri;
                   11072:     }
                   11073: 
                   11074:     if (!$udom || !$uname || !$file) {
                   11075: 	# unable to handle the uri
                   11076: 	return ();
                   11077:     }
1.956     raeburn  11078:     my $getpropath;
                   11079:     if ($file =~ /^userfiles\//) {
                   11080:         $getpropath = 1;
                   11081:     }
1.1136    raeburn  11082:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11083:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11084:         return ();
                   11085:     } else {
                   11086:         if (ref($listref) eq 'ARRAY') {
                   11087:             my @stats = split('&',$listref->[0]);
                   11088: 	    shift(@stats); #filename is first
                   11089: 	    return @stats;
                   11090:         }
1.712     albertel 11091:     }
                   11092:     return ();
                   11093: }
                   11094: 
1.26      www      11095: # -------------------------------------------------------- Value of a Condition
                   11096: 
1.713     albertel 11097: # gets the value of a specific preevaluated condition
                   11098: #    stored in the string  $env{user.state.<cid>}
                   11099: # or looks up a condition reference in the bighash and if if hasn't
                   11100: # already been evaluated recurses into docondval to get the value of
                   11101: # the condition, then memoizing it to 
                   11102: #   $env{user.state.<cid>.<condition>}
1.40      www      11103: sub directcondval {
                   11104:     my $number=shift;
1.620     albertel 11105:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11106: 	&Apache::lonuserstate::evalstate();
                   11107:     }
1.713     albertel 11108:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11109: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11110:     } elsif ($number =~ /^_/) {
                   11111: 	my $sub_condition;
                   11112: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11113: 		&GDBM_READER(),0640)) {
                   11114: 	    $sub_condition=$bighash{'conditions'.$number};
                   11115: 	    untie(%bighash);
                   11116: 	}
                   11117: 	my $value = &docondval($sub_condition);
1.949     raeburn  11118: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11119: 	return $value;
                   11120:     }
1.620     albertel 11121:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11122:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11123:     } else {
                   11124:        return 2;
                   11125:     }
                   11126: }
                   11127: 
1.713     albertel 11128: # get the collection of conditions for this resource
1.26      www      11129: sub condval {
                   11130:     my $condidx=shift;
1.54      www      11131:     my $allpathcond='';
1.713     albertel 11132:     foreach my $cond (split(/\|/,$condidx)) {
                   11133: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11134: 	    $allpathcond.=
                   11135: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11136: 	}
1.191     harris41 11137:     }
1.54      www      11138:     $allpathcond=~s/\|$//;
1.713     albertel 11139:     return &docondval($allpathcond);
                   11140: }
                   11141: 
                   11142: #evaluates an expression of conditions
                   11143: sub docondval {
                   11144:     my ($allpathcond) = @_;
                   11145:     my $result=0;
                   11146:     if ($env{'request.course.id'}
                   11147: 	&& defined($allpathcond)) {
                   11148: 	my $operand='|';
                   11149: 	my @stack;
                   11150: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11151: 	    if ($chunk eq '(') {
                   11152: 		push @stack,($operand,$result);
                   11153: 	    } elsif ($chunk eq ')') {
                   11154: 		my $before=pop @stack;
                   11155: 		if (pop @stack eq '&') {
                   11156: 		    $result=$result>$before?$before:$result;
                   11157: 		} else {
                   11158: 		    $result=$result>$before?$result:$before;
                   11159: 		}
                   11160: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11161: 		$operand=$chunk;
                   11162: 	    } else {
                   11163: 		my $new=directcondval($chunk);
                   11164: 		if ($operand eq '&') {
                   11165: 		    $result=$result>$new?$new:$result;
                   11166: 		} else {
                   11167: 		    $result=$result>$new?$result:$new;
                   11168: 		}
                   11169: 	    }
                   11170: 	}
1.26      www      11171:     }
                   11172:     return $result;
1.421     albertel 11173: }
                   11174: 
                   11175: # ---------------------------------------------------- Devalidate courseresdata
                   11176: 
                   11177: sub devalidatecourseresdata {
                   11178:     my ($coursenum,$coursedomain)=@_;
                   11179:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11180:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11181: }
                   11182: 
1.763     www      11183: 
1.200     www      11184: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11185: #
                   11186: #  Parameters:
                   11187: #      $coursenum    - Number of the course.
                   11188: #      $coursedomain - Domain at which the course was created.
                   11189: #  Returns:
                   11190: #     A hash of the course parameters along (I think) with timestamps
                   11191: #     and version info.
1.877     foxr     11192: 
1.624     albertel 11193: sub get_courseresdata {
                   11194:     my ($coursenum,$coursedomain)=@_;
1.200     www      11195:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11196:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11197:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11198:     my %dumpreply;
1.417     albertel 11199:     unless (defined($cached)) {
1.624     albertel 11200: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11201: 	$result=\%dumpreply;
1.251     albertel 11202: 	my ($tmp) = keys(%dumpreply);
                   11203: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11204: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11205: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11206: 	    return $tmp;
1.416     albertel 11207: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11208: 	    $result=undef;
1.599     albertel 11209: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11210: 	}
                   11211:     }
1.624     albertel 11212:     return $result;
                   11213: }
                   11214: 
1.633     albertel 11215: sub devalidateuserresdata {
                   11216:     my ($uname,$udom)=@_;
                   11217:     my $hashid="$udom:$uname";
                   11218:     &devalidate_cache_new('userres',$hashid);
                   11219: }
                   11220: 
1.624     albertel 11221: sub get_userresdata {
                   11222:     my ($uname,$udom)=@_;
                   11223:     #most student don\'t have any data set, check if there is some data
                   11224:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11225: 
                   11226:     my $hashid="$udom:$uname";
                   11227:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11228:     if (!defined($cached)) {
                   11229: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11230: 	$result=\%resourcedata;
                   11231: 	&do_cache_new('userres',$hashid,$result,600);
                   11232:     }
                   11233:     my ($tmp)=keys(%$result);
                   11234:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11235: 	return $result;
                   11236:     }
                   11237:     #error 2 occurs when the .db doesn't exist
                   11238:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11239:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11240: 	    &logthis("<font color=\"blue\">WARNING:".
                   11241: 		     " Trying to get resource data for ".
                   11242: 		     $uname." at ".$udom.": ".
                   11243: 		     $tmp."</font>");
                   11244:         }
1.624     albertel 11245:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11246: 	#&EXT_cache_set($udom,$uname);
                   11247: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11248: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11249:     }
                   11250:     return $tmp;
                   11251: }
1.879     foxr     11252: #----------------------------------------------- resdata - return resource data
                   11253: #  Purpose:
                   11254: #    Return resource data for either users or for a course.
                   11255: #  Parameters:
                   11256: #     $name      - Course/user name.
                   11257: #     $domain    - Name of the domain the user/course is registered on.
                   11258: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11259: #     @which     - Array of names of resources desired.
                   11260: #  Returns:
                   11261: #     The value of the first reasource in @which that is found in the
                   11262: #     resource hash.
                   11263: #  Exceptional Conditions:
                   11264: #     If the $type passed in is not valid (not the string 'course' or 
                   11265: #     'user', an undefined  reference is returned.
                   11266: #     If none of the resources are found, an undef is returned
1.624     albertel 11267: sub resdata {
                   11268:     my ($name,$domain,$type,@which)=@_;
                   11269:     my $result;
                   11270:     if ($type eq 'course') {
                   11271: 	$result=&get_courseresdata($name,$domain);
                   11272:     } elsif ($type eq 'user') {
                   11273: 	$result=&get_userresdata($name,$domain);
                   11274:     }
                   11275:     if (!ref($result)) { return $result; }    
1.251     albertel 11276:     foreach my $item (@which) {
1.927     albertel 11277: 	if (defined($result->{$item->[0]})) {
                   11278: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11279: 	}
1.250     albertel 11280:     }
1.291     albertel 11281:     return undef;
1.200     www      11282: }
                   11283: 
1.1172.2.31  raeburn  11284: sub get_numsuppfiles {
                   11285:     my ($cnum,$cdom,$ignorecache)=@_;
                   11286:     my $hashid=$cnum.':'.$cdom;
                   11287:     my ($suppcount,$cached);
                   11288:     unless ($ignorecache) {
                   11289:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11290:     }
                   11291:     unless (defined($cached)) {
                   11292:         my $chome=&homeserver($cnum,$cdom);
                   11293:         unless ($chome eq 'no_host') {
                   11294:             ($suppcount,my $errors) = (0,0);
                   11295:             my $suppmap = 'supplemental.sequence';
                   11296:             ($suppcount,$errors) =
                   11297:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11298:         }
                   11299:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11300:     }
                   11301:     return $suppcount;
                   11302: }
                   11303: 
1.379     matthew  11304: #
                   11305: # EXT resource caching routines
                   11306: #
                   11307: 
                   11308: sub clear_EXT_cache_status {
1.383     albertel 11309:     &delenv('cache.EXT.');
1.379     matthew  11310: }
                   11311: 
                   11312: sub EXT_cache_status {
                   11313:     my ($target_domain,$target_user) = @_;
1.383     albertel 11314:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11315:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11316:         # We know already the user has no data
                   11317:         return 1;
                   11318:     } else {
                   11319:         return 0;
                   11320:     }
                   11321: }
                   11322: 
                   11323: sub EXT_cache_set {
                   11324:     my ($target_domain,$target_user) = @_;
1.383     albertel 11325:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11326:     #&appenv({$cachename => time});
1.379     matthew  11327: }
                   11328: 
1.28      www      11329: # --------------------------------------------------------- Value of a Variable
1.58      www      11330: sub EXT {
1.715     albertel 11331: 
1.1172.2.28  raeburn  11332:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11333:     unless ($varname) { return ''; }
1.218     albertel 11334:     #get real user name/domain, courseid and symb
                   11335:     my $courseid;
1.359     albertel 11336:     my $publicuser;
1.427     www      11337:     if ($symbparm) {
                   11338: 	$symbparm=&get_symb_from_alias($symbparm);
                   11339:     }
1.218     albertel 11340:     if (!($uname && $udom)) {
1.790     albertel 11341:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11342:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11343:     } else {
1.620     albertel 11344: 	$courseid=$env{'request.course.id'};
1.218     albertel 11345:     }
1.48      www      11346:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11347:     my $rest;
1.320     albertel 11348:     if (defined($therest[0])) {
1.48      www      11349:        $rest=join('.',@therest);
                   11350:     } else {
                   11351:        $rest='';
                   11352:     }
1.320     albertel 11353: 
1.57      www      11354:     my $qualifierrest=$qualifier;
                   11355:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11356:     my $spacequalifierrest=$space;
                   11357:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11358:     if ($realm eq 'user') {
1.48      www      11359: # --------------------------------------------------------------- user.resource
                   11360: 	if ($space eq 'resource') {
1.651     albertel 11361: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11362: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11363: 		 &&
1.744     albertel 11364: 		 ($symbparm eq &symbread()) ) {	
                   11365: 		# if we are in the middle of processing the resource the
                   11366: 		# get the value we are planning on committing
                   11367:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11368:                     return $Apache::lonhomework::results{$qualifierrest};
                   11369:                 } else {
                   11370:                     return $Apache::lonhomework::history{$qualifierrest};
                   11371:                 }
1.335     albertel 11372: 	    } else {
1.359     albertel 11373: 		my %restored;
1.620     albertel 11374: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11375: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11376: 		} else {
                   11377: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11378: 		}
1.335     albertel 11379: 		return $restored{$qualifierrest};
                   11380: 	    }
1.48      www      11381: # ----------------------------------------------------------------- user.access
                   11382:         } elsif ($space eq 'access') {
1.218     albertel 11383: 	    # FIXME - not supporting calls for a specific user
1.48      www      11384:             return &allowed($qualifier,$rest);
                   11385: # ------------------------------------------ user.preferences, user.environment
                   11386:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11387: 	    if (($uname eq $env{'user.name'}) &&
                   11388: 		($udom eq $env{'user.domain'})) {
                   11389: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11390: 	    } else {
1.359     albertel 11391: 		my %returnhash;
                   11392: 		if (!$publicuser) {
                   11393: 		    %returnhash=&userenvironment($udom,$uname,
                   11394: 						 $qualifierrest);
                   11395: 		}
1.218     albertel 11396: 		return $returnhash{$qualifierrest};
                   11397: 	    }
1.48      www      11398: # ----------------------------------------------------------------- user.course
                   11399:         } elsif ($space eq 'course') {
1.218     albertel 11400: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11401:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11402: # ------------------------------------------------------------------- user.role
                   11403:         } elsif ($space eq 'role') {
1.218     albertel 11404: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11405:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11406:             if ($qualifier eq 'value') {
                   11407: 		return $role;
                   11408:             } elsif ($qualifier eq 'extent') {
                   11409:                 return $where;
                   11410:             }
                   11411: # ----------------------------------------------------------------- user.domain
                   11412:         } elsif ($space eq 'domain') {
1.218     albertel 11413:             return $udom;
1.48      www      11414: # ------------------------------------------------------------------- user.name
                   11415:         } elsif ($space eq 'name') {
1.218     albertel 11416:             return $uname;
1.48      www      11417: # ---------------------------------------------------- Any other user namespace
1.29      www      11418:         } else {
1.359     albertel 11419: 	    my %reply;
                   11420: 	    if (!$publicuser) {
                   11421: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11422: 	    }
                   11423: 	    return $reply{$qualifierrest};
1.48      www      11424:         }
1.236     www      11425:     } elsif ($realm eq 'query') {
                   11426: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11427:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11428: 						[$spacequalifierrest]);
1.620     albertel 11429: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11430:    } elsif ($realm eq 'request') {
1.48      www      11431: # ------------------------------------------------------------- request.browser
                   11432:         if ($space eq 'browser') {
1.1145    bisitz   11433:             return $env{'browser.'.$qualifier};
1.57      www      11434: # ------------------------------------------------------------ request.filename
                   11435:         } else {
1.620     albertel 11436:             return $env{'request.'.$spacequalifierrest};
1.29      www      11437:         }
1.28      www      11438:     } elsif ($realm eq 'course') {
1.48      www      11439: # ---------------------------------------------------------- course.description
1.620     albertel 11440:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11441:     } elsif ($realm eq 'resource') {
1.165     www      11442: 
1.620     albertel 11443: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11444: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11445: 	}
1.693     albertel 11446: 
1.1172.2.30  raeburn  11447:         if ($qualifier eq '') {
                   11448: 	    if ($space eq 'title') {
                   11449: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11450: 	        return &gettitle($symbparm);
                   11451: 	    }
1.693     albertel 11452: 	
1.1172.2.30  raeburn  11453: 	    if ($space eq 'map') {
                   11454: 	        my ($map) = &decode_symb($symbparm);
                   11455: 	        return &symbread($map);
                   11456: 	    }
                   11457:             if ($space eq 'maptitle') {
                   11458:                 my ($map) = &decode_symb($symbparm);
                   11459:                 return &gettitle($map);
                   11460:             }
                   11461: 	    if ($space eq 'filename') {
                   11462: 	        if ($symbparm) {
                   11463: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11464: 	        }
                   11465: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11466: 	    }
1.1172.2.30  raeburn  11467: 
                   11468:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11469:                 if ($space eq 'visibleparts') {
                   11470:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11471:                     my $item;
                   11472:                     if (ref($navmap)) {
                   11473:                         my $res = $navmap->getBySymb($symbparm);
                   11474:                         my $parts = $res->parts();
                   11475:                         if (ref($parts) eq 'ARRAY') {
                   11476:                             $item = join(',',@{$parts});
                   11477:                         }
                   11478:                         undef($navmap);
                   11479:                     }
                   11480:                     return $item;
                   11481:                 }
                   11482:             }
                   11483:         }
1.693     albertel 11484: 
                   11485: 	my ($section, $group, @groups);
1.593     albertel 11486: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11487:         if (($courseid eq '') && ($cid)) {
                   11488:             $courseid = $cid;
                   11489:         }
                   11490: 	if (($symbparm && $courseid) && 
                   11491: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11492: 
1.218     albertel 11493: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11494: 
1.60      www      11495: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11496: 	    my $symbp=$symbparm;
1.735     albertel 11497: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11498: 
                   11499: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11500: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11501: 
1.620     albertel 11502: 	    if (($env{'user.name'} eq $uname) &&
                   11503: 		($env{'user.domain'} eq $udom)) {
                   11504: 		$section=$env{'request.course.sec'};
1.733     raeburn  11505:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11506:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11507: 	    } else {
1.539     albertel 11508: 		if (! defined($usection)) {
1.551     albertel 11509: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11510: 		} else {
                   11511: 		    $section = $usection;
                   11512: 		}
1.733     raeburn  11513:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11514: 	    }
                   11515: 
                   11516: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11517: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11518: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11519: 
1.593     albertel 11520: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11521: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11522: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11523: 
1.60      www      11524: # ----------------------------------------------------------- first, check user
1.624     albertel 11525: 
                   11526: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11527: 				       ([$courselevelr,'resource'],
                   11528: 					[$courselevelm,'map'     ],
                   11529: 					[$courselevel, 'course'  ]));
1.931     albertel 11530: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11531: 
1.594     albertel 11532: # ------------------------------------------------ second, check some of course
1.684     raeburn  11533:             my $coursereply;
1.691     raeburn  11534:             if (@groups > 0) {
                   11535:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11536:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11537:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11538:             }
1.96      www      11539: 
1.684     raeburn  11540: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11541: 				  $env{'course.'.$courseid.'.domain'},
                   11542: 				  'course',
                   11543: 				  ([$seclevelr,   'resource'],
                   11544: 				   [$seclevelm,   'map'     ],
                   11545: 				   [$seclevel,    'course'  ],
                   11546: 				   [$courselevelr,'resource']));
                   11547: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11548: 
1.60      www      11549: # ------------------------------------------------------ third, check map parms
1.218     albertel 11550: 	    my %parmhash=();
                   11551: 	    my $thisparm='';
                   11552: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11553: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11554: 		    &GDBM_READER(),0640)) {
1.218     albertel 11555: 		$thisparm=$parmhash{$symbparm};
                   11556: 		untie(%parmhash);
                   11557: 	    }
1.927     albertel 11558: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11559: 	}
1.594     albertel 11560: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11561: 
1.218     albertel 11562: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11563: 	my $filename;
                   11564: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11565: 	if ($symbparm) {
1.409     www      11566: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11567: 	} else {
1.620     albertel 11568: 	    $filename=$env{'request.filename'};
1.282     albertel 11569: 	}
                   11570: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11571: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11572: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11573: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11574: 
1.927     albertel 11575: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11576: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11577: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11578: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11579: 				     $env{'course.'.$courseid.'.domain'},
                   11580: 				     'course',
1.927     albertel 11581: 				     ([$courselevelm,'map'   ],
                   11582: 				      [$courselevel, 'course']));
                   11583: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11584: 	}
1.145     www      11585: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11586: 	unless ($space eq '0') {
1.336     albertel 11587: 	    my @parts=split(/_/,$space);
                   11588: 	    my $id=pop(@parts);
                   11589: 	    my $part=join('_',@parts);
                   11590: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11591: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11592: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11593: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11594: 	}
1.395     albertel 11595: 	if ($recurse) { return undef; }
                   11596: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11597: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11598: # ---------------------------------------------------- Any other user namespace
                   11599:     } elsif ($realm eq 'environment') {
                   11600: # ----------------------------------------------------------------- environment
1.620     albertel 11601: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11602: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11603: 	} else {
1.770     albertel 11604: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11605: 		return '';
                   11606: 	    }
1.219     albertel 11607: 	    my %returnhash=&userenvironment($udom,$uname,
                   11608: 					    $spacequalifierrest);
                   11609: 	    return $returnhash{$spacequalifierrest};
                   11610: 	}
1.28      www      11611:     } elsif ($realm eq 'system') {
1.48      www      11612: # ----------------------------------------------------------------- system.time
                   11613: 	if ($space eq 'time') {
                   11614: 	    return time;
                   11615:         }
1.696     albertel 11616:     } elsif ($realm eq 'server') {
                   11617: # ----------------------------------------------------------------- system.time
                   11618: 	if ($space eq 'name') {
                   11619: 	    return $ENV{'SERVER_NAME'};
                   11620:         }
1.28      www      11621:     }
1.48      www      11622:     return '';
1.61      www      11623: }
                   11624: 
1.927     albertel 11625: sub get_reply {
                   11626:     my ($reply_value) = @_;
1.940     raeburn  11627:     if (ref($reply_value) eq 'ARRAY') {
                   11628:         if (wantarray) {
                   11629: 	    return @$reply_value;
                   11630:         }
                   11631:         return $reply_value->[0];
                   11632:     } else {
                   11633:         return $reply_value;
1.927     albertel 11634:     }
                   11635: }
                   11636: 
1.691     raeburn  11637: sub check_group_parms {
                   11638:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11639:     my @groupitems = ();
                   11640:     my $resultitem;
1.927     albertel 11641:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11642:     foreach my $group (@{$groups}) {
                   11643:         foreach my $level (@levels) {
1.927     albertel 11644:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11645:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11646:         }
                   11647:     }
                   11648:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11649:                             $env{'course.'.$courseid.'.domain'},
                   11650:                                      'course',@groupitems);
                   11651:     return $coursereply;
                   11652: }
                   11653: 
                   11654: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11655:     my ($courseid,@groups) = @_;
                   11656:     @groups = sort(@groups);
1.691     raeburn  11657:     return @groups;
                   11658: }
                   11659: 
1.395     albertel 11660: sub packages_tab_default {
                   11661:     my ($uri,$varname)=@_;
                   11662:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11663: 
                   11664:     my (@extension,@specifics,$do_default);
                   11665:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11666: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11667: 	if ($pack_type eq 'default') {
                   11668: 	    $do_default=1;
                   11669: 	} elsif ($pack_type eq 'extension') {
                   11670: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11671: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11672: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11673: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11674: 	}
                   11675:     }
                   11676:     # first look for a package that matches the requested part id
                   11677:     foreach my $package (@specifics) {
                   11678: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11679: 	next if ($pack_part ne $part);
                   11680: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11681: 	    return $packagetab{"$pack_type&$name&default"};
                   11682: 	}
                   11683:     }
                   11684:     # look for any possible matching non extension_ package
                   11685:     foreach my $package (@specifics) {
                   11686: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11687: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11688: 	    return $packagetab{"$pack_type&$name&default"};
                   11689: 	}
1.585     albertel 11690: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11691: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11692: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11693: 	}
                   11694:     }
1.738     albertel 11695:     # look for any posible extension_ match
                   11696:     foreach my $package (@extension) {
                   11697: 	my ($package,$pack_type)=@{$package};
                   11698: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11699: 	    return $packagetab{"$pack_type&$name&default"};
                   11700: 	}
                   11701: 	if (defined($packagetab{$package."&$name&default"})) {
                   11702: 	    return $packagetab{$package."&$name&default"};
                   11703: 	}
                   11704:     }
                   11705:     # look for a global default setting
                   11706:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11707: 	return $packagetab{"default&$name&default"};
                   11708:     }
1.395     albertel 11709:     return undef;
                   11710: }
                   11711: 
1.334     albertel 11712: sub add_prefix_and_part {
                   11713:     my ($prefix,$part)=@_;
                   11714:     my $keyroot;
                   11715:     if (defined($prefix) && $prefix !~ /^__/) {
                   11716: 	# prefix that has a part already
                   11717: 	$keyroot=$prefix;
                   11718:     } elsif (defined($prefix)) {
                   11719: 	# prefix that is missing a part
                   11720: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11721:     } else {
                   11722: 	# no prefix at all
                   11723: 	if (defined($part)) { $keyroot='_'.$part; }
                   11724:     }
                   11725:     return $keyroot;
                   11726: }
                   11727: 
1.71      www      11728: # ---------------------------------------------------------------- Get metadata
                   11729: 
1.599     albertel 11730: my %metaentry;
1.1070    www      11731: my %importedpartids;
1.1172.2.99  raeburn  11732: my %importedrespids;
1.71      www      11733: sub metadata {
1.176     www      11734:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11735:     $uri=&declutter($uri);
1.288     albertel 11736:     # if it is a non metadata possible uri return quickly
1.529     albertel 11737:     if (($uri eq '') || 
                   11738: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11739: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11740:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11741: 	return undef;
                   11742:     }
1.1172.2.49  raeburn  11743:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11744: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11745: 	return undef;
1.288     albertel 11746:     }
1.73      www      11747:     my $filename=$uri;
                   11748:     $uri=~s/\.meta$//;
1.172     www      11749: #
                   11750: # Is the metadata already cached?
1.177     www      11751: # Look at timestamp of caching
1.172     www      11752: # Everything is cached by the main uri, libraries are never directly cached
                   11753: #
1.428     albertel 11754:     if (!defined($liburi)) {
1.599     albertel 11755: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11756: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11757:     }
                   11758:     {
1.1069    www      11759: # Imported parts would go here
1.1172.2.99  raeburn  11760:         my @origfiletagids=();
1.1069    www      11761:         my $importedparts=0;
1.1172.2.99  raeburn  11762: 
                   11763: # Imported responseids would go here
                   11764:         my $importedresponses=0;
1.172     www      11765: #
                   11766: # Is this a recursive call for a library?
                   11767: #
1.599     albertel 11768: #	if (! exists($metacache{$uri})) {
                   11769: #	    $metacache{$uri}={};
                   11770: #	}
1.924     albertel 11771: 	my $cachetime = 60*60;
1.171     www      11772:         if ($liburi) {
                   11773: 	    $liburi=&declutter($liburi);
                   11774:             $filename=$liburi;
1.401     bowersj2 11775:         } else {
1.599     albertel 11776: 	    &devalidate_cache_new('meta',$uri);
                   11777: 	    undef(%metaentry);
1.401     bowersj2 11778: 	}
1.140     www      11779:         my %metathesekeys=();
1.73      www      11780:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11781: 	my $metastring;
1.1140    www      11782: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11783: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11784: 	    $metastring = 
1.929     albertel 11785: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11786: 					  ('grade_target' => 'meta'));
                   11787: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11788: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11789:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11790: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11791: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11792: 	    $metastring=&getfile($file);
1.489     albertel 11793: 	}
1.208     albertel 11794:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11795:         my $token;
1.140     www      11796:         undef %metathesekeys;
1.71      www      11797:         while ($token=$parser->get_token) {
1.339     albertel 11798: 	    if ($token->[0] eq 'S') {
                   11799: 		if (defined($token->[2]->{'package'})) {
1.172     www      11800: #
                   11801: # This is a package - get package info
                   11802: #
1.339     albertel 11803: 		    my $package=$token->[2]->{'package'};
                   11804: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11805: 		    if (defined($token->[2]->{'id'})) { 
                   11806: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11807: 		    }
1.599     albertel 11808: 		    if ($metaentry{':packages'}) {
                   11809: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11810: 		    } else {
1.599     albertel 11811: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11812: 		    }
1.736     albertel 11813: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11814: 			my $part=$keyroot;
                   11815: 			$part=~s/^\_//;
1.736     albertel 11816: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11817: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11818: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11819: 			    # ignore package.tab specified default values
                   11820:                             # here &package_tab_default() will fetch those
                   11821: 			    if ($subp eq 'default') { next; }
1.736     albertel 11822: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11823: 			    my $unikey;
                   11824: 			    if ($pack =~ /_0$/) {
                   11825: 				$unikey='parameter_0_'.$name;
                   11826: 				$part=0;
                   11827: 			    } else {
                   11828: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11829: 			    }
1.339     albertel 11830: 			    if ($subp eq 'display') {
                   11831: 				$value.=' [Part: '.$part.']';
                   11832: 			    }
1.599     albertel 11833: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11834: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11835: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11836: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11837: 			    }
1.599     albertel 11838: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11839: 				$metaentry{':'.$unikey}=
                   11840: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11841: 			    }
1.339     albertel 11842: 			}
                   11843: 		    }
                   11844: 		} else {
1.172     www      11845: #
                   11846: # This is not a package - some other kind of start tag
1.339     albertel 11847: #
                   11848: 		    my $entry=$token->[1];
1.1068    www      11849: 		    my $unikey='';
1.175     www      11850: 
1.339     albertel 11851: 		    if ($entry eq 'import') {
1.175     www      11852: #
                   11853: # Importing a library here
1.339     albertel 11854: #
1.1067    www      11855:                         my $location=$parser->get_text('/import');
                   11856:                         my $dir=$filename;
                   11857:                         $dir=~s|[^/]*$||;
                   11858:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11859: 
                   11860:                         my $importid=$token->[2]->{'id'};
1.1068    www      11861:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11862: #
                   11863: # Check metadata for imported file to
                   11864: # see if it contained response items
                   11865: #
                   11866:                         my %currmetaentry = %metaentry;
                   11867:                         my $libresponseorder = &metadata($location,'responseorder');
                   11868:                         my $origfile;
                   11869:                         if ($libresponseorder ne '') {
                   11870:                             if ($#origfiletagids<0) {
                   11871:                                 undef(%importedrespids);
                   11872:                                 undef(%importedpartids);
                   11873:                             }
                   11874:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11875:                             if (@{$importedrespids{$importid}} > 0) {
                   11876:                                 $importedresponses = 1;
                   11877: # We need to get the original file and the imported file to get the response order correct
                   11878: # Load and inspect original file
                   11879:                                 if ($#origfiletagids<0) {
                   11880:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11881:                                     $origfile=&getfile($origfilelocation);
                   11882:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11883:                                 }
                   11884:                             }
                   11885:                         }
                   11886: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11887: # hash populated for imported library file
                   11888:                         %metaentry = %currmetaentry;
                   11889:                         undef(%currmetaentry);
1.1068    www      11890:                         if ($importmode eq 'problem') {
1.1069    www      11891: # Import as problem/response
1.1068    www      11892:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11893:                         } elsif ($importmode eq 'part') {
                   11894: # Import as part(s)
1.1069    www      11895:                            $importedparts=1;
                   11896: # We need to get the original file and the imported file to get the part order correct
                   11897: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11898: # Load and inspect original file if we didn't do that already
                   11899:                            if ($#origfiletagids<0) {
                   11900:                                undef(%importedrespids);
                   11901:                                undef(%importedpartids);
                   11902:                                if ($origfile eq '') {
                   11903:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11904:                                    $origfile=&getfile($origfilelocation);
                   11905:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11906:                                }
1.1070    www      11907:                            }
                   11908: 
1.1069    www      11909: # Load and inspect imported file
                   11910:                            my $impfile=&getfile($location);
                   11911:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11912:                            if ($#impfilepartids>=0) {
                   11913: # This problem had parts
1.1070    www      11914:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11915:                            } else {
                   11916: # Importing by turning a single problem into a problem part
                   11917: # It gets the import-tags ID as part-ID
                   11918:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11919:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11920:                            }
1.1068    www      11921:                         } else {
                   11922: # Normal import
                   11923:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11924:                            if (defined($token->[2]->{'id'})) {
                   11925:                               $unikey.='_'.$token->[2]->{'id'};
                   11926:                            }
1.1067    www      11927:                         }
                   11928: 
1.339     albertel 11929: 			if ($depthcount<20) {
1.736     albertel 11930: 			    my $metadata = 
                   11931: 				&metadata($uri,'keys', $location,$unikey,
                   11932: 					  $depthcount+1);
                   11933: 			    foreach my $meta (split(',',$metadata)) {
                   11934: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11935: 				$metathesekeys{$meta}=1;
1.339     albertel 11936: 			    }
1.1068    www      11937: 			
                   11938:                         }
1.1067    www      11939: 		    } else {
                   11940: #
                   11941: # Not importing, some other kind of non-package, non-library start tag
                   11942: # 
                   11943:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11944:                         if (defined($token->[2]->{'id'})) {
                   11945:                             $unikey.='_'.$token->[2]->{'id'};
                   11946:                         }
1.339     albertel 11947: 			if (defined($token->[2]->{'name'})) { 
                   11948: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11949: 			}
                   11950: 			$metathesekeys{$unikey}=1;
1.736     albertel 11951: 			foreach my $param (@{$token->[3]}) {
                   11952: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11953: 				$token->[2]->{$param};
1.339     albertel 11954: 			}
                   11955: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11956: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11957: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11958: 		 # only ws inside the tag, and not in default, so use default
                   11959: 		 # as value
1.599     albertel 11960: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11961: 			} elsif ( $internaltext =~ /\S/ ) {
                   11962: 		  # something interesting inside the tag
                   11963: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11964: 			} else {
1.908     albertel 11965: 		  # no interesting values, don't set a default
1.339     albertel 11966: 			}
1.172     www      11967: # end of not-a-package not-a-library import
1.339     albertel 11968: 		    }
1.172     www      11969: # end of not-a-package start tag
1.339     albertel 11970: 		}
1.172     www      11971: # the next is the end of "start tag"
1.339     albertel 11972: 	    }
                   11973: 	}
1.483     albertel 11974: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11975: 	$extension = lc($extension);
                   11976: 	if ($extension eq 'htm') { $extension='html'; }
                   11977: 
1.737     albertel 11978: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11979: 	    #no specific packages #how's our extension
                   11980: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11981: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11982: 					 \%metathesekeys);
                   11983: 	}
1.883     albertel 11984: 
                   11985: 	if (!exists($metaentry{':packages'})
                   11986: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11987: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11988: 		#no specific packages well let's get default then
                   11989: 		if ($key!~/^default&/) { next; }
1.488     albertel 11990: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11991: 					     \%metathesekeys);
                   11992: 	    }
                   11993: 	}
1.338     www      11994: # are there custom rights to evaluate
1.599     albertel 11995: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11996: 
1.338     www      11997:     #
                   11998:     # Importing a rights file here
1.339     albertel 11999:     #
                   12000: 	    unless ($depthcount) {
1.599     albertel 12001: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12002: 		my $dir=$filename;
                   12003: 		$dir=~s|[^/]*$||;
                   12004: 		$location=&filelocation($dir,$location);
1.736     albertel 12005: 		my $rights_metadata =
                   12006: 		    &metadata($uri,'keys',$location,'_rights',
                   12007: 			      $depthcount+1);
                   12008: 		foreach my $rights (split(',',$rights_metadata)) {
                   12009: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12010: 		    $metathesekeys{$rights}=1;
1.339     albertel 12011: 		}
                   12012: 	    }
                   12013: 	}
1.737     albertel 12014: 	# uniqifiy package listing
                   12015: 	my %seen;
                   12016: 	my @uniq_packages =
                   12017: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12018: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12019: 
1.1172.2.99  raeburn  12020:         if (($importedresponses) || ($importedparts)) {
                   12021:             if ($importedparts) {
1.1070    www      12022: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12023:                 $metaentry{':partorder'}='';
                   12024:                 $metathesekeys{'partorder'}=1;
                   12025:             }
                   12026:             if ($importedresponses) {
                   12027: # We had imported responses and need to rebuild responseorder
                   12028:                 $metaentry{':responseorder'}='';
                   12029:                 $metathesekeys{'responseorder'}=1;
                   12030:             }
                   12031:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12032:                 my $origid = $origfiletagids[$index+1];
                   12033:                 if ($origfiletagids[$index] eq 'part') {
                   12034: # Original part, part of the problem
                   12035:                     if ($importedparts) {
                   12036:                         $metaentry{':partorder'}.=','.$origid;
                   12037:                     }
                   12038:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12039:                     if ($importedparts) {
                   12040: # We have imported parts at this position
                   12041:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12042:                     }
                   12043:                     if ($importedresponses) {
                   12044: # We have imported responses at this position
                   12045:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12046:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12047:                         }
                   12048:                     }
                   12049:                 } else {
                   12050: # Original response item, part of the problem
                   12051:                     if ($importedresponses) {
                   12052:                         $metaentry{':responseorder'}.=','.$origid;
                   12053:                     }
                   12054:                 }
                   12055:             }
                   12056:             if ($importedparts) {
                   12057:                 $metaentry{':partorder'}=~s/^\,//;
                   12058:             }
                   12059:             if ($importedresponses) {
                   12060:                 $metaentry{':responseorder'}=~s/^\,//;
                   12061:             }
1.1070    www      12062:         }
                   12063: 
1.737     albertel 12064: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12065: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12066: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12067: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12068: # this is the end of "was not already recently cached
1.71      www      12069:     }
1.599     albertel 12070:     return $metaentry{':'.$what};
1.261     albertel 12071: }
                   12072: 
1.488     albertel 12073: sub metadata_create_package_def {
1.483     albertel 12074:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12075:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12076:     if ($subp eq 'default') { next; }
                   12077:     
1.599     albertel 12078:     if (defined($metaentry{':packages'})) {
                   12079: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12080:     } else {
1.599     albertel 12081: 	$metaentry{':packages'}=$package;
1.483     albertel 12082:     }
                   12083:     my $value=$packagetab{$key};
                   12084:     my $unikey;
                   12085:     $unikey='parameter_0_'.$name;
1.599     albertel 12086:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12087:     $$metathesekeys{$unikey}=1;
1.599     albertel 12088:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12089: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12090:     }
1.599     albertel 12091:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12092: 	$metaentry{':'.$unikey}=
                   12093: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12094:     }
                   12095: }
                   12096: 
1.261     albertel 12097: sub metadata_generate_part0 {
                   12098:     my ($metadata,$metacache,$uri) = @_;
                   12099:     my %allnames;
1.737     albertel 12100:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12101: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12102: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12103: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12104: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12105: 	    $allnames{$name}=$part;
                   12106: 	  }
                   12107: 	}
                   12108:     }
                   12109:     foreach my $name (keys(%allnames)) {
                   12110:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12111:       my $key=":parameter_0_$name";
1.261     albertel 12112:       $$metacache{"$key.part"}='0';
                   12113:       $$metacache{"$key.name"}=$name;
1.428     albertel 12114:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12115: 					   $allnames{$name}.'_'.$name.
                   12116: 					   '.type'};
1.428     albertel 12117:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12118: 			     '.display'};
1.644     www      12119:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12120:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12121:       $$metacache{"$key.display"}=$olddis;
                   12122:     }
1.71      www      12123: }
                   12124: 
1.764     albertel 12125: # ------------------------------------------------------ Devalidate title cache
                   12126: 
                   12127: sub devalidate_title_cache {
                   12128:     my ($url)=@_;
                   12129:     if (!$env{'request.course.id'}) { return; }
                   12130:     my $symb=&symbread($url);
                   12131:     if (!$symb) { return; }
                   12132:     my $key=$env{'request.course.id'}."\0".$symb;
                   12133:     &devalidate_cache_new('title',$key);
                   12134: }
                   12135: 
1.1014    droeschl 12136: # ------------------------------------------------- Get the title of a course
                   12137: 
                   12138: sub current_course_title {
                   12139:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12140: }
1.301     www      12141: # ------------------------------------------------- Get the title of a resource
                   12142: 
                   12143: sub gettitle {
                   12144:     my $urlsymb=shift;
                   12145:     my $symb=&symbread($urlsymb);
1.534     albertel 12146:     if ($symb) {
1.620     albertel 12147: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12148: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12149: 	if (defined($cached)) { 
                   12150: 	    return $result;
                   12151: 	}
1.534     albertel 12152: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12153: 	my $title='';
1.907     albertel 12154: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12155: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12156: 	} else {
                   12157: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12158: 		    &GDBM_READER(),0640)) {
                   12159: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12160: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12161: 		untie(%bighash);
                   12162: 	    }
1.534     albertel 12163: 	}
                   12164: 	$title=~s/\&colon\;/\:/gs;
                   12165: 	if ($title) {
1.1159    www      12166: # Remember both $symb and $title for dynamic metadata
                   12167:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12168:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12169: # Cache this title and then return it
1.599     albertel 12170: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12171: 	}
                   12172: 	$urlsymb=$url;
                   12173:     }
                   12174:     my $title=&metadata($urlsymb,'title');
                   12175:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12176:     return $title;
1.301     www      12177: }
1.613     albertel 12178: 
1.614     albertel 12179: sub get_slot {
                   12180:     my ($which,$cnum,$cdom)=@_;
                   12181:     if (!$cnum || !$cdom) {
1.790     albertel 12182: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12183: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12184: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12185:     }
1.703     albertel 12186:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12187:     my %slotinfo;
                   12188:     if (exists($remembered{$key})) {
                   12189: 	$slotinfo{$which} = $remembered{$key};
                   12190:     } else {
                   12191: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12192: 	&Apache::lonhomework::showhash(%slotinfo);
                   12193: 	my ($tmp)=keys(%slotinfo);
                   12194: 	if ($tmp=~/^error:/) { return (); }
                   12195: 	$remembered{$key} = $slotinfo{$which};
                   12196:     }
1.616     albertel 12197:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12198: 	return %{$slotinfo{$which}};
                   12199:     }
                   12200:     return $slotinfo{$which};
1.614     albertel 12201: }
1.1150    raeburn  12202: 
                   12203: sub get_reservable_slots {
                   12204:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12205:     my $now = time;
                   12206:     my $reservable_info;
                   12207:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12208:     if (exists($remembered{$key})) {
                   12209:         $reservable_info = $remembered{$key};
                   12210:     } else {
                   12211:         my %resv;
                   12212:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12213:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12214:         $reservable_info = \%resv;
                   12215:         $remembered{$key} = $reservable_info;
                   12216:     }
                   12217:     return $reservable_info;
                   12218: }
                   12219: 
                   12220: sub get_course_slots {
                   12221:     my ($cnum,$cdom) = @_;
                   12222:     my $hashid=$cnum.':'.$cdom;
                   12223:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12224:     if (defined($cached)) {
                   12225:         if (ref($result) eq 'HASH') {
                   12226:             return %{$result};
                   12227:         }
                   12228:     } else {
                   12229:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12230:         my ($tmp) = keys(%slots);
                   12231:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12232:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12233:             return %slots;
                   12234:         }
                   12235:     }
                   12236:     return;
                   12237: }
                   12238: 
                   12239: sub devalidate_slots_cache {
                   12240:     my ($cnum,$cdom)=@_;
                   12241:     my $hashid=$cnum.':'.$cdom;
                   12242:     &devalidate_cache_new('allslots',$hashid);
                   12243: }
                   12244: 
1.1172.2.8  raeburn  12245: sub get_coursechange {
                   12246:     my ($cdom,$cnum) = @_;
                   12247:     if ($cdom eq '' || $cnum eq '') {
                   12248:         return unless ($env{'request.course.id'});
                   12249:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12250:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12251:     }
                   12252:     my $hashid=$cdom.'_'.$cnum;
                   12253:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12254:     if ((defined($cached)) && ($change ne '')) {
                   12255:         return $change;
                   12256:     } else {
                   12257:         my %crshash;
                   12258:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12259:         if ($crshash{'internal.contentchange'} eq '') {
                   12260:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12261:             if ($change eq '') {
                   12262:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12263:                 $change = $crshash{'internal.created'};
                   12264:             }
                   12265:         } else {
                   12266:             $change = $crshash{'internal.contentchange'};
                   12267:         }
                   12268:         my $cachetime = 600;
                   12269:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12270:     }
                   12271:     return $change;
                   12272: }
                   12273: 
                   12274: sub devalidate_coursechange_cache {
                   12275:     my ($cnum,$cdom)=@_;
                   12276:     my $hashid=$cnum.':'.$cdom;
                   12277:     &devalidate_cache_new('crschange',$hashid);
                   12278: }
                   12279: 
1.31      www      12280: # ------------------------------------------------- Update symbolic store links
                   12281: 
                   12282: sub symblist {
                   12283:     my ($mapname,%newhash)=@_;
1.438     www      12284:     $mapname=&deversion(&declutter($mapname));
1.31      www      12285:     my %hash;
1.620     albertel 12286:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12287:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12288:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12289: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12290: 		next if ($url eq 'last_known'
                   12291: 			 && $env{'form.no_update_last_known'});
                   12292: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12293: 						    $newhash{$url}->[1],
                   12294: 						    $newhash{$url}->[0]);
1.191     harris41 12295:             }
1.31      www      12296:             if (untie(%hash)) {
                   12297: 		return 'ok';
                   12298:             }
                   12299:         }
                   12300:     }
                   12301:     return 'error';
1.212     www      12302: }
                   12303: 
                   12304: # --------------------------------------------------------------- Verify a symb
                   12305: 
                   12306: sub symbverify {
1.1172.2.11  raeburn  12307:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12308:     my $thisfn=$thisurl;
1.439     www      12309:     $thisfn=&declutter($thisfn);
1.215     www      12310: # direct jump to resource in page or to a sequence - will construct own symbs
                   12311:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12312: # check URL part
1.409     www      12313:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12314: 
1.431     www      12315:     unless ($url eq $thisfn) { return 0; }
1.213     www      12316: 
1.216     www      12317:     $symb=&symbclean($symb);
1.510     www      12318:     $thisurl=&deversion($thisurl);
1.439     www      12319:     $thisfn=&deversion($thisfn);
1.213     www      12320: 
                   12321:     my %bighash;
                   12322:     my $okay=0;
1.431     www      12323: 
1.620     albertel 12324:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12325:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12326:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12327:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12328:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12329:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12330:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12331:             }
                   12332:         }
                   12333:         my $ids;
1.1172.2.122  raeburn  12334:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12335:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12336:         } else {
                   12337:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12338:         }
1.1102    raeburn  12339:         unless ($ids) {
1.1172.2.13  raeburn  12340:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12341:             $ids=$bighash{$idkey};
1.216     www      12342:         }
                   12343:         if ($ids) {
                   12344: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12345:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12346:                 $symb =~ s/\?.+$//;
                   12347:             }
1.800     albertel 12348: 	    foreach my $id (split(/\,/,$ids)) {
                   12349: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12350:                if (
                   12351:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12352:    eq $symb) {
1.1172.2.11  raeburn  12353:                    if (ref($encstate)) {
                   12354:                        $$encstate = $bighash{'encrypted_'.$id};
                   12355:                    }
1.1172.2.13  raeburn  12356:                    if (($env{'request.role.adv'}) ||
                   12357:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12358:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12359:                        $okay=1;
                   12360:                        last;
                   12361:                    }
                   12362:                }
                   12363:            }
1.216     www      12364:         }
1.213     www      12365: 	untie(%bighash);
                   12366:     }
                   12367:     return $okay;
1.31      www      12368: }
                   12369: 
1.210     www      12370: # --------------------------------------------------------------- Clean-up symb
                   12371: 
                   12372: sub symbclean {
                   12373:     my $symb=shift;
1.568     albertel 12374:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12375: # remove version from map
                   12376:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12377: 
1.210     www      12378: # remove version from URL
                   12379:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12380: 
1.507     www      12381: # remove wrapper
                   12382: 
1.510     www      12383:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12384:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12385:     return $symb;
1.409     www      12386: }
                   12387: 
                   12388: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12389: 
                   12390: sub encode_symb {
                   12391:     my ($map,$resid,$url)=@_;
                   12392:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12393: }
1.409     www      12394: 
                   12395: sub decode_symb {
1.568     albertel 12396:     my $symb=shift;
                   12397:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12398:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12399:     return (&fixversion($map),$resid,&fixversion($url));
                   12400: }
                   12401: 
                   12402: sub fixversion {
                   12403:     my $fn=shift;
1.609     banghart 12404:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12405:     my %bighash;
                   12406:     my $uri=&clutter($fn);
1.620     albertel 12407:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12408: # is this cached?
1.599     albertel 12409:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12410:     if (defined($cached)) { return $result; }
                   12411: # unfortunately not cached, or expired
1.620     albertel 12412:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12413: 	    &GDBM_READER(),0640)) {
                   12414:  	if ($bighash{'version_'.$uri}) {
                   12415:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12416:  	    unless (($version eq 'mostrecent') || 
                   12417: 		    ($version==&getversion($uri))) {
1.440     www      12418:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12419:  	    }
                   12420:  	}
                   12421:  	untie %bighash;
1.413     www      12422:     }
1.599     albertel 12423:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12424: }
                   12425: 
                   12426: sub deversion {
                   12427:     my $url=shift;
                   12428:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12429:     return $url;
1.210     www      12430: }
                   12431: 
1.31      www      12432: # ------------------------------------------------------ Return symb list entry
                   12433: 
                   12434: sub symbread {
1.1172.2.66  raeburn  12435:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12436:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12437:     if (defined($env{$cache_str})) {
                   12438:         if ($ignorecachednull) {
                   12439:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12440:         } else {
                   12441:             return $env{$cache_str};
                   12442:         }
                   12443:     }
1.242     www      12444: # no filename provided? try from environment
1.1172.2.54  raeburn  12445:     unless ($thisfn) {
1.620     albertel 12446:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12447:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12448:         }
                   12449:         $thisfn=$env{'request.filename'};
1.44      www      12450:     }
1.569     albertel 12451:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12452: # is that filename actually a symb? Verify, clean, and return
                   12453:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12454: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12455: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12456: 	}
1.242     www      12457:     }
1.44      www      12458:     $thisfn=declutter($thisfn);
1.31      www      12459:     my %hash;
1.37      www      12460:     my %bighash;
                   12461:     my $syval='';
1.620     albertel 12462:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12463:         my $targetfn = $thisfn;
1.609     banghart 12464:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12465:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12466:         }
1.687     albertel 12467: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12468: 	    $targetfn=$1;
                   12469: 	}
1.620     albertel 12470:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12471:                       &GDBM_READER(),0640)) {
1.481     raeburn  12472: 	    $syval=$hash{$targetfn};
1.37      www      12473:             untie(%hash);
                   12474:         }
                   12475: # ---------------------------------------------------------- There was an entry
                   12476:         if ($syval) {
1.601     albertel 12477: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12478: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12479: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12480: 		    #return $env{$cache_str}='';
1.601     albertel 12481: 		#}    
                   12482: 		#$syval.=$1;
                   12483: 	    #}
1.37      www      12484:         } else {
                   12485: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12486:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12487:                             &GDBM_READER(),0640)) {
1.37      www      12488: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12489:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12490:               unless ($ids) { 
                   12491:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12492:               }
                   12493:               unless ($ids) {
                   12494: # alias?
                   12495: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12496:               }
1.37      www      12497:               if ($ids) {
                   12498: # ------------------------------------------------------------------- Has ID(s)
                   12499:                  my @possibilities=split(/\,/,$ids);
1.39      www      12500:                  if ($#possibilities==0) {
                   12501: # ----------------------------------------------- There is only one possibility
1.37      www      12502: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12503: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12504: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12505:                      if (ref($possibles) eq 'HASH') {
                   12506:                          $possibles->{$syval} = 1;
                   12507:                      }
                   12508:                      if ($checkforblock) {
                   12509:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12510:                          if (@blockers) {
                   12511:                              $syval = '';
                   12512:                              return;
                   12513:                          }
                   12514:                      }
                   12515:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12516: # ------------------------------------------ There is more than one possibility
                   12517:                      my $realpossible=0;
1.800     albertel 12518:                      foreach my $id (@possibilities) {
                   12519: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12520:                          my $canaccess;
                   12521:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12522:                              $canaccess = 1;
                   12523:                          } else {
                   12524:                              $canaccess = &allowed('bre',$file);
                   12525:                          }
                   12526:                          if ($canaccess) {
                   12527:          		     my ($mapid,$resid)=split(/\./,$id);
                   12528:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12529:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12530:                                                              $resid,$thisfn);
                   12531:                                  if (ref($possibles) eq 'HASH') {
                   12532:                                      $possibles->{$syval} = 1;
                   12533:                                  }
                   12534:                                  if ($checkforblock) {
                   12535:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12536:                                      unless (@blockers > 0) {
                   12537:                                          $syval = $poss_syval;
                   12538:                                          $realpossible++;
                   12539:                                      }
                   12540:                                  } else {
                   12541:                                      $syval = $poss_syval;
                   12542:                                      $realpossible++;
                   12543:                                  }
                   12544:                              }
1.39      www      12545: 			 }
1.191     harris41 12546:                      }
1.39      www      12547: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12548:                  } else {
                   12549:                      $syval='';
1.37      www      12550:                  }
                   12551: 	      }
1.1172.2.66  raeburn  12552:               untie(%bighash);
1.481     raeburn  12553:            }
1.31      www      12554:         }
1.62      www      12555:         if ($syval) {
1.620     albertel 12556: 	    return $env{$cache_str}=$syval;
1.62      www      12557:         }
1.31      www      12558:     }
1.949     raeburn  12559:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12560:     return $env{$cache_str}='';
1.31      www      12561: }
                   12562: 
                   12563: # ---------------------------------------------------------- Return random seed
                   12564: 
1.32      www      12565: sub numval {
                   12566:     my $txt=shift;
                   12567:     $txt=~tr/A-J/0-9/;
                   12568:     $txt=~tr/a-j/0-9/;
                   12569:     $txt=~tr/K-T/0-9/;
                   12570:     $txt=~tr/k-t/0-9/;
                   12571:     $txt=~tr/U-Z/0-5/;
                   12572:     $txt=~tr/u-z/0-5/;
                   12573:     $txt=~s/\D//g;
1.564     albertel 12574:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12575:     return int($txt);
1.368     albertel 12576: }
                   12577: 
1.484     albertel 12578: sub numval2 {
                   12579:     my $txt=shift;
                   12580:     $txt=~tr/A-J/0-9/;
                   12581:     $txt=~tr/a-j/0-9/;
                   12582:     $txt=~tr/K-T/0-9/;
                   12583:     $txt=~tr/k-t/0-9/;
                   12584:     $txt=~tr/U-Z/0-5/;
                   12585:     $txt=~tr/u-z/0-5/;
                   12586:     $txt=~s/\D//g;
                   12587:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12588:     my $total;
                   12589:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12590:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12591:     return int($total);
                   12592: }
                   12593: 
1.575     albertel 12594: sub numval3 {
                   12595:     use integer;
                   12596:     my $txt=shift;
                   12597:     $txt=~tr/A-J/0-9/;
                   12598:     $txt=~tr/a-j/0-9/;
                   12599:     $txt=~tr/K-T/0-9/;
                   12600:     $txt=~tr/k-t/0-9/;
                   12601:     $txt=~tr/U-Z/0-5/;
                   12602:     $txt=~tr/u-z/0-5/;
                   12603:     $txt=~s/\D//g;
                   12604:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12605:     my $total;
                   12606:     foreach my $val (@txts) { $total+=$val; }
                   12607:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12608:     return $total;
                   12609: }
                   12610: 
1.675     albertel 12611: sub digest {
                   12612:     my ($data)=@_;
                   12613:     my $digest=&Digest::MD5::md5($data);
                   12614:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12615:     my ($e,$f);
                   12616:     {
                   12617:         use integer;
                   12618:         $e=($a+$b);
                   12619:         $f=($c+$d);
                   12620:         if ($_64bit) {
                   12621:             $e=(($e<<32)>>32);
                   12622:             $f=(($f<<32)>>32);
                   12623:         }
                   12624:     }
                   12625:     if (wantarray) {
                   12626: 	return ($e,$f);
                   12627:     } else {
                   12628: 	my $g;
                   12629: 	{
                   12630: 	    use integer;
                   12631: 	    $g=($e+$f);
                   12632: 	    if ($_64bit) {
                   12633: 		$g=(($g<<32)>>32);
                   12634: 	    }
                   12635: 	}
                   12636: 	return $g;
                   12637:     }
                   12638: }
                   12639: 
1.368     albertel 12640: sub latest_rnd_algorithm_id {
1.675     albertel 12641:     return '64bit5';
1.366     albertel 12642: }
1.32      www      12643: 
1.503     albertel 12644: sub get_rand_alg {
                   12645:     my ($courseid)=@_;
1.790     albertel 12646:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12647:     if ($courseid) {
1.620     albertel 12648: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12649:     }
                   12650:     return &latest_rnd_algorithm_id();
                   12651: }
                   12652: 
1.562     albertel 12653: sub validCODE {
                   12654:     my ($CODE)=@_;
                   12655:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12656:     return 0;
                   12657: }
                   12658: 
1.491     albertel 12659: sub getCODE {
1.620     albertel 12660:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12661:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12662: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12663: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12664: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12665:     }
                   12666:     return undef;
                   12667: }
1.1133    foxr     12668: #
                   12669: #  Determines the random seed for a specific context:
                   12670: #
                   12671: # parameters:
                   12672: #   symb      - in course context the symb for the seed.
                   12673: #   course_id - The course id of the form domain_coursenum.
                   12674: #   domain    - Domain for the user.
                   12675: #   course    - Course for the user.
                   12676: #   cenv      - environment of the course.
                   12677: #
                   12678: # NOTE:
                   12679: #   All parameters are picked out of the environment if missing
                   12680: #   or not defined.
                   12681: #   If a symb cannot be determined the current time is used instead.
                   12682: #
                   12683: #  For a given well defined symb, courside, domain, username,
                   12684: #  and course environment, the seed is reproducible.
                   12685: #
1.31      www      12686: sub rndseed {
1.1133    foxr     12687:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12688:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12689:     if (!defined($symb)) {
1.366     albertel 12690: 	unless ($symb=$wsymb) { return time; }
                   12691:     }
1.1146    foxr     12692:     if (!defined $courseid) { 
                   12693: 	$courseid=$wcourseid; 
                   12694:     }
                   12695:     if (!defined $domain) { $domain=$wdomain; }
                   12696:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12697: 
                   12698:     my $which;
                   12699:     if (defined($cenv->{'rndseed'})) {
                   12700: 	$which = $cenv->{'rndseed'};
                   12701:     } else {
                   12702: 	$which =&get_rand_alg($courseid);
                   12703:     }
1.491     albertel 12704:     if (defined(&getCODE())) {
1.675     albertel 12705: 	if ($which eq '64bit5') {
                   12706: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12707: 	} elsif ($which eq '64bit4') {
1.575     albertel 12708: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12709: 	} else {
                   12710: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12711: 	}
1.675     albertel 12712:     } elsif ($which eq '64bit5') {
                   12713: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12714:     } elsif ($which eq '64bit4') {
                   12715: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12716:     } elsif ($which eq '64bit3') {
                   12717: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12718:     } elsif ($which eq '64bit2') {
                   12719: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12720:     } elsif ($which eq '64bit') {
                   12721: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12722:     }
                   12723:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12724: }
                   12725: 
                   12726: sub rndseed_32bit {
                   12727:     my ($symb,$courseid,$domain,$username)=@_;
                   12728:     {
                   12729: 	use integer;
                   12730: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12731: 	my $symbseed=numval($symb) << 22;
                   12732: 	my $namechck=unpack("%32C*",$username) << 17;
                   12733: 	my $nameseed=numval($username) << 12;
                   12734: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12735: 	my $courseseed=unpack("%32C*",$courseid);
                   12736: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12737: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12738: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12739: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12740: 	return $num;
                   12741:     }
                   12742: }
                   12743: 
                   12744: sub rndseed_64bit {
                   12745:     my ($symb,$courseid,$domain,$username)=@_;
                   12746:     {
                   12747: 	use integer;
                   12748: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12749: 	my $symbseed=numval($symb) << 10;
                   12750: 	my $namechck=unpack("%32S*",$username);
                   12751: 	
                   12752: 	my $nameseed=numval($username) << 21;
                   12753: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12754: 	my $courseseed=unpack("%32S*",$courseid);
                   12755: 	
                   12756: 	my $num1=$symbchck+$symbseed+$namechck;
                   12757: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12758: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12759: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12760: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12761: 	return "$num1,$num2";
1.155     albertel 12762:     }
1.366     albertel 12763: }
                   12764: 
1.443     albertel 12765: sub rndseed_64bit2 {
                   12766:     my ($symb,$courseid,$domain,$username)=@_;
                   12767:     {
                   12768: 	use integer;
                   12769: 	# strings need to be an even # of cahracters long, it it is odd the
                   12770:         # last characters gets thrown away
                   12771: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12772: 	my $symbseed=numval($symb) << 10;
                   12773: 	my $namechck=unpack("%32S*",$username.' ');
                   12774: 	
                   12775: 	my $nameseed=numval($username) << 21;
1.501     albertel 12776: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12777: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12778: 	
                   12779: 	my $num1=$symbchck+$symbseed+$namechck;
                   12780: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12781: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12782: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12783: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12784: 	return "$num1,$num2";
                   12785:     }
                   12786: }
                   12787: 
                   12788: sub rndseed_64bit3 {
                   12789:     my ($symb,$courseid,$domain,$username)=@_;
                   12790:     {
                   12791: 	use integer;
                   12792: 	# strings need to be an even # of cahracters long, it it is odd the
                   12793:         # last characters gets thrown away
                   12794: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12795: 	my $symbseed=numval2($symb) << 10;
                   12796: 	my $namechck=unpack("%32S*",$username.' ');
                   12797: 	
                   12798: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12799: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12800: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12801: 	
                   12802: 	my $num1=$symbchck+$symbseed+$namechck;
                   12803: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12804: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12805: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12806: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12807: 	
1.503     albertel 12808: 	return "$num1:$num2";
1.443     albertel 12809:     }
                   12810: }
                   12811: 
1.575     albertel 12812: sub rndseed_64bit4 {
                   12813:     my ($symb,$courseid,$domain,$username)=@_;
                   12814:     {
                   12815: 	use integer;
                   12816: 	# strings need to be an even # of cahracters long, it it is odd the
                   12817:         # last characters gets thrown away
                   12818: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12819: 	my $symbseed=numval3($symb) << 10;
                   12820: 	my $namechck=unpack("%32S*",$username.' ');
                   12821: 	
                   12822: 	my $nameseed=numval3($username) << 21;
                   12823: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12824: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12825: 	
                   12826: 	my $num1=$symbchck+$symbseed+$namechck;
                   12827: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12828: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12829: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12830: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12831: 	
1.575     albertel 12832: 	return "$num1:$num2";
                   12833:     }
                   12834: }
                   12835: 
1.675     albertel 12836: sub rndseed_64bit5 {
                   12837:     my ($symb,$courseid,$domain,$username)=@_;
                   12838:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12839:     return "$num1:$num2";
                   12840: }
                   12841: 
1.366     albertel 12842: sub rndseed_CODE_64bit {
                   12843:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12844:     {
1.366     albertel 12845: 	use integer;
1.443     albertel 12846: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12847: 	my $symbseed=numval2($symb);
1.491     albertel 12848: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12849: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12850: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12851: 	my $num1=$symbseed+$CODEchck;
                   12852: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12853: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12854: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12855: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12856: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12857: 	return "$num1:$num2";
1.366     albertel 12858:     }
                   12859: }
                   12860: 
1.575     albertel 12861: sub rndseed_CODE_64bit4 {
                   12862:     my ($symb,$courseid,$domain,$username)=@_;
                   12863:     {
                   12864: 	use integer;
                   12865: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12866: 	my $symbseed=numval3($symb);
                   12867: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12868: 	my $CODEseed=numval3(&getCODE());
                   12869: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12870: 	my $num1=$symbseed+$CODEchck;
                   12871: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12872: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12873: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12874: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12875: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12876: 	return "$num1:$num2";
                   12877:     }
                   12878: }
                   12879: 
1.675     albertel 12880: sub rndseed_CODE_64bit5 {
                   12881:     my ($symb,$courseid,$domain,$username)=@_;
                   12882:     my $code = &getCODE();
                   12883:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12884:     return "$num1:$num2";
                   12885: }
                   12886: 
1.366     albertel 12887: sub setup_random_from_rndseed {
                   12888:     my ($rndseed)=@_;
1.503     albertel 12889:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12890: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12891:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12892:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12893:         } else {
                   12894:             &Math::Random::random_set_seed($num1,$num2);
                   12895:         }
1.366     albertel 12896:     } else {
                   12897: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12898:     }
1.36      albertel 12899: }
                   12900: 
1.474     albertel 12901: sub latest_receipt_algorithm_id {
1.835     albertel 12902:     return 'receipt3';
1.474     albertel 12903: }
                   12904: 
1.480     www      12905: sub recunique {
                   12906:     my $fucourseid=shift;
                   12907:     my $unique;
1.835     albertel 12908:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12909: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12910: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12911:     } else {
                   12912: 	$unique=$perlvar{'lonReceipt'};
                   12913:     }
                   12914:     return unpack("%32C*",$unique);
                   12915: }
                   12916: 
                   12917: sub recprefix {
                   12918:     my $fucourseid=shift;
                   12919:     my $prefix;
1.835     albertel 12920:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12921: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12922: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12923:     } else {
                   12924: 	$prefix=$perlvar{'lonHostID'};
                   12925:     }
                   12926:     return unpack("%32C*",$prefix);
                   12927: }
                   12928: 
1.76      www      12929: sub ireceipt {
1.474     albertel 12930:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12931: 
                   12932:     my $return =&recprefix($fucourseid).'-';
                   12933: 
                   12934:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12935: 	$env{'request.state'} eq 'construct') {
                   12936: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12937: 	return $return;
                   12938:     }
                   12939: 
1.76      www      12940:     my $cuname=unpack("%32C*",$funame);
                   12941:     my $cudom=unpack("%32C*",$fudom);
                   12942:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12943:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12944:     my $cunique=&recunique($fucourseid);
1.474     albertel 12945:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12946:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12947: 
1.790     albertel 12948: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12949: 			       
                   12950: 	$return.= ($cunique%$cuname+
                   12951: 		   $cunique%$cudom+
                   12952: 		   $cusymb%$cuname+
                   12953: 		   $cusymb%$cudom+
                   12954: 		   $cucourseid%$cuname+
                   12955: 		   $cucourseid%$cudom+
                   12956: 		   $cpart%$cuname+
                   12957: 		   $cpart%$cudom);
                   12958:     } else {
                   12959: 	$return.= ($cunique%$cuname+
                   12960: 		   $cunique%$cudom+
                   12961: 		   $cusymb%$cuname+
                   12962: 		   $cusymb%$cudom+
                   12963: 		   $cucourseid%$cuname+
                   12964: 		   $cucourseid%$cudom);
                   12965:     }
                   12966:     return $return;
1.76      www      12967: }
                   12968: 
                   12969: sub receipt {
1.474     albertel 12970:     my ($part)=@_;
1.790     albertel 12971:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12972:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12973: }
1.260     ng       12974: 
1.790     albertel 12975: sub whichuser {
                   12976:     my ($passedsymb)=@_;
                   12977:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12978:     if (defined($env{'form.grade_symb'})) {
                   12979: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12980: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12981: 	if (!$allowed &&
                   12982: 	    exists($env{'request.course.sec'}) &&
                   12983: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12984: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12985: 			      '/'.$env{'request.course.sec'});
                   12986: 	}
                   12987: 	if ($allowed) {
                   12988: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12989: 	    $courseid=$tmp_courseid;
                   12990: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12991: 	    ($name)=&get_env_multiple('form.grade_username');
                   12992: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12993: 	}
                   12994:     }
                   12995:     if (!$passedsymb) {
                   12996: 	$symb=&symbread();
                   12997:     } else {
                   12998: 	$symb=$passedsymb;
                   12999:     }
                   13000:     $courseid=$env{'request.course.id'};
                   13001:     $domain=$env{'user.domain'};
                   13002:     $name=$env{'user.name'};
                   13003:     if ($name eq 'public' && $domain eq 'public') {
                   13004: 	if (!defined($env{'form.username'})) {
                   13005: 	    $env{'form.username'}.=time.rand(10000000);
                   13006: 	}
                   13007: 	$name.=$env{'form.username'};
                   13008:     }
                   13009:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13010: 
                   13011: }
                   13012: 
1.36      albertel 13013: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13014: # returns either the contents of the file or 
                   13015: # -1 if the file doesn't exist
1.481     raeburn  13016: #
                   13017: # if the target is a file that was uploaded via DOCS, 
                   13018: # a check will be made to see if a current copy exists on the local server,
                   13019: # if it does this will be served, otherwise a copy will be retrieved from
                   13020: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13021: # the local server.   
1.472     albertel 13022: 
1.36      albertel 13023: sub getfile {
1.538     albertel 13024:     my ($file) = @_;
1.609     banghart 13025:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13026:     &repcopy($file);
                   13027:     return &readfile($file);
                   13028: }
                   13029: 
                   13030: sub repcopy_userfile {
                   13031:     my ($file)=@_;
1.1142    raeburn  13032:     my $londocroot = $perlvar{'lonDocRoot'};
                   13033:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13034:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13035:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13036: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13037:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13038:     if (-e "$file") {
1.828     www      13039: # we already have a local copy, check it out
1.538     albertel 13040: 	my @fileinfo = stat($file);
1.828     www      13041: 	my $rtncode;
                   13042: 	my $info;
1.538     albertel 13043: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13044: 	if ($lwpresp ne 'ok') {
1.828     www      13045: # there is no such file anymore, even though we had a local copy
1.482     albertel 13046: 	    if ($rtncode eq '404') {
1.538     albertel 13047: 		unlink($file);
1.482     albertel 13048: 	    }
                   13049: 	    return -1;
                   13050: 	}
                   13051: 	if ($info < $fileinfo[9]) {
1.828     www      13052: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13053: 	    return 'ok';
1.828     www      13054: 	} else {
                   13055: # the file is outdated, get rid of it
                   13056: 	    unlink($file);
1.482     albertel 13057: 	}
1.828     www      13058:     }
                   13059: # one way or the other, at this point, we don't have the file
                   13060: # construct the correct path for the file
                   13061:     my @parts = ($cdom,$cnum); 
                   13062:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13063: 	push @parts, split(/\//,$1);
                   13064:     }
                   13065:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13066:     foreach my $part (@parts) {
                   13067: 	$path .= '/'.$part;
                   13068: 	if (!-e $path) {
                   13069: 	    mkdir($path,0770);
1.482     albertel 13070: 	}
                   13071:     }
1.828     www      13072: # now the path exists for sure
                   13073: # get a user agent
                   13074:     my $ua=new LWP::UserAgent;
                   13075:     my $transferfile=$file.'.in.transfer';
                   13076: # FIXME: this should flock
                   13077:     if (-e $transferfile) { return 'ok'; }
                   13078:     my $request;
                   13079:     $uri=~s/^\///;
1.980     raeburn  13080:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13081:     my $hostname = &hostname($homeserver);
1.980     raeburn  13082:     my $protocol = $protocol{$homeserver};
                   13083:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13084:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13085:     my $response=$ua->request($request,$transferfile);
                   13086: # did it work?
                   13087:     if ($response->is_error()) {
                   13088: 	unlink($transferfile);
                   13089: 	&logthis("Userfile repcopy failed for $uri");
                   13090: 	return -1;
                   13091:     }
                   13092: # worked, rename the transfer file
                   13093:     rename($transferfile,$file);
1.607     raeburn  13094:     return 'ok';
1.481     raeburn  13095: }
                   13096: 
1.517     albertel 13097: sub tokenwrapper {
                   13098:     my $uri=shift;
1.980     raeburn  13099:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13100:     $uri=~s|^/||;
1.620     albertel 13101:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13102:     my $token=$1;
1.552     albertel 13103:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13104:     if ($udom && $uname && $file) {
                   13105: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13106:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13107:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13108:         my $hostname = &hostname($homeserver);
1.980     raeburn  13109:         my $protocol = $protocol{$homeserver};
                   13110:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13111:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13112:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13113:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13114:     } else {
                   13115:         return '/adm/notfound.html';
                   13116:     }
                   13117: }
                   13118: 
1.828     www      13119: # call with reqtype HEAD: get last modification time
                   13120: # call with reqtype GET: get the file contents
                   13121: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13122: #
1.481     raeburn  13123: sub getuploaded {
                   13124:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13125:     $uri=~s/^\///;
1.980     raeburn  13126:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13127:     my $hostname = &hostname($homeserver);
1.980     raeburn  13128:     my $protocol = $protocol{$homeserver};
                   13129:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13130:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13131:     my $ua=new LWP::UserAgent;
                   13132:     my $request=new HTTP::Request($reqtype,$uri);
                   13133:     my $response=$ua->request($request);
                   13134:     $$rtncode = $response->code;
1.482     albertel 13135:     if (! $response->is_success()) {
                   13136: 	return 'failed';
                   13137:     }      
                   13138:     if ($reqtype eq 'HEAD') {
1.486     www      13139: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13140:     } elsif ($reqtype eq 'GET') {
                   13141: 	$$info = $response->content;
1.472     albertel 13142:     }
1.482     albertel 13143:     return 'ok';
1.36      albertel 13144: }
                   13145: 
1.481     raeburn  13146: sub readfile {
                   13147:     my $file = shift;
                   13148:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13149:     my $fh;
1.1172.2.96  raeburn  13150:     open($fh,"<",$file);
1.481     raeburn  13151:     my $a='';
1.800     albertel 13152:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13153:     return $a;
                   13154: }
                   13155: 
1.36      albertel 13156: sub filelocation {
1.590     banghart 13157:     my ($dir,$file) = @_;
                   13158:     my $location;
                   13159:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13160: 
                   13161:     if ($file =~ m-^/adm/-) {
                   13162: 	$file=~s-^/adm/wrapper/-/-;
                   13163: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13164:     }
1.882     albertel 13165: 
1.1139    www      13166:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13167:         $location = $file;
1.609     banghart 13168:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13169:         my ($udom,$uname,$filename)=
1.811     albertel 13170:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13171:         my $home=&homeserver($uname,$udom);
                   13172:         my $is_me=0;
                   13173:         my @ids=&current_machine_ids();
                   13174:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13175:         if ($is_me) {
1.1117    foxr     13176:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13177:         } else {
                   13178:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13179:   	      $udom.'/'.$uname.'/'.$filename;
                   13180:         }
1.882     albertel 13181:     } elsif ($file =~ m-^/adm/-) {
                   13182: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13183:     } else {
                   13184:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13185:         $file=~s:^/(res|priv)/:/:;
                   13186:         my $space=$1;
1.590     banghart 13187:         if ( !( $file =~ m:^/:) ) {
                   13188:             $location = $dir. '/'.$file;
                   13189:         } else {
1.1142    raeburn  13190:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13191:         }
1.59      albertel 13192:     }
1.590     banghart 13193:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13194:     while ($location=~m{/\.\./}) {
                   13195: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13196: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13197: 	} else {
                   13198: 	    $location=~ s{/\.\./}{/}g;
                   13199: 	}
                   13200:     } #remove dir/..
1.590     banghart 13201:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13202:     return $location;
1.46      www      13203: }
1.36      albertel 13204: 
1.46      www      13205: sub hreflocation {
                   13206:     my ($dir,$file)=@_;
1.980     raeburn  13207:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13208: 	$file=filelocation($dir,$file);
1.700     albertel 13209:     } elsif ($file=~m-^/adm/-) {
                   13210: 	$file=~s-^/adm/wrapper/-/-;
                   13211: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13212:     }
                   13213:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13214: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13215:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13216: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13217: 	        {/uploaded/$1/$2/}x;
1.46      www      13218:     }
1.913     albertel 13219:     if ($file=~ m{^/userfiles/}) {
                   13220: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13221:     }
1.462     albertel 13222:     return $file;
1.465     albertel 13223: }
                   13224: 
1.1139    www      13225: 
                   13226: 
                   13227: 
                   13228: 
1.465     albertel 13229: sub current_machine_domains {
1.853     albertel 13230:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13231: }
                   13232: 
                   13233: sub machine_domains {
                   13234:     my ($hostname) = @_;
1.465     albertel 13235:     my @domains;
1.838     albertel 13236:     my %hostname = &all_hostnames();
1.465     albertel 13237:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13238: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13239: 	if ($hostname eq $name) {
1.844     albertel 13240: 	    push(@domains,&host_domain($id));
1.465     albertel 13241: 	}
                   13242:     }
                   13243:     return @domains;
                   13244: }
                   13245: 
                   13246: sub current_machine_ids {
1.853     albertel 13247:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13248: }
                   13249: 
                   13250: sub machine_ids {
                   13251:     my ($hostname) = @_;
                   13252:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13253:     my @ids;
1.888     albertel 13254:     my %name_to_host = &all_names();
1.889     albertel 13255:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13256: 	return @{ $name_to_host{$hostname} };
                   13257:     }
                   13258:     return;
1.31      www      13259: }
                   13260: 
1.824     raeburn  13261: sub additional_machine_domains {
                   13262:     my @domains;
1.1172.2.96  raeburn  13263:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13264:     while( my $line = <$fh>) {
                   13265:         $line =~ s/\s//g;
                   13266:         push(@domains,$line);
                   13267:     }
                   13268:     return @domains;
                   13269: }
                   13270: 
                   13271: sub default_login_domain {
                   13272:     my $domain = $perlvar{'lonDefDomain'};
                   13273:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13274:     foreach my $posdom (&current_machine_domains(),
                   13275:                         &additional_machine_domains()) {
                   13276:         if (lc($posdom) eq lc($testdomain)) {
                   13277:             $domain=$posdom;
                   13278:             last;
                   13279:         }
                   13280:     }
                   13281:     return $domain;
                   13282: }
                   13283: 
1.1172.2.106  raeburn  13284: sub shared_institution {
                   13285:     my ($dom) = @_;
                   13286:     my $same_intdom;
                   13287:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13288:     if ($hostintdom ne '') {
                   13289:         my %iphost = &get_iphost();
                   13290:         my $primary_id = &domain($dom,'primary');
                   13291:         my $primary_ip = &get_host_ip($primary_id);
                   13292:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13293:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13294:                 my $intdom = &internet_dom($id);
                   13295:                 if ($intdom eq $hostintdom) {
                   13296:                     $same_intdom = 1;
                   13297:                     last;
                   13298:                 }
                   13299:             }
                   13300:         }
                   13301:     }
                   13302:     return $same_intdom;
                   13303: }
                   13304: 
1.1172.2.120  raeburn  13305: sub uses_sts {
                   13306:     my ($ignore_cache) = @_;
                   13307:     my $lonhost = $perlvar{'lonHostID'};
                   13308:     my $hostname = &hostname($lonhost);
                   13309:     my $sts_on;
                   13310:     if ($protocol{$lonhost} eq 'https') {
                   13311:         my $cachetime = 12*3600;
                   13312:         if (!$ignore_cache) {
                   13313:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13314:             if (defined($cached)) {
                   13315:                 return $sts_on;
                   13316:             }
                   13317:         }
1.1172.2.121  raeburn  13318:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13319:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13320:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13321:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13322:         if ($response->is_success) {
                   13323:             my $has_sts = $response->header('Strict-Transport-Security');
                   13324:             if ($has_sts eq '') {
                   13325:                 $sts_on = 0;
                   13326:             } else {
                   13327:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13328:                     my $maxage = $1;
                   13329:                     if ($maxage) {
                   13330:                         $sts_on = 1;
                   13331:                     } else {
                   13332:                         $sts_on = 0;
                   13333:                     }
                   13334:                 } else {
                   13335:                     $sts_on = 0;
                   13336:                 }
                   13337:             }
                   13338:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13339:         }
                   13340:     }
                   13341:     return;
                   13342: }
                   13343: 
1.31      www      13344: # ------------------------------------------------------------- Declutters URLs
                   13345: 
                   13346: sub declutter {
                   13347:     my $thisfn=shift;
1.569     albertel 13348:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13349:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13350:         $thisfn=~s{^/home/httpd/html}{};
                   13351:     }
1.31      www      13352:     $thisfn=~s/^\///;
1.697     albertel 13353:     $thisfn=~s|^adm/wrapper/||;
                   13354:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13355:     $thisfn=~s/^res\///;
1.1172    bisitz   13356:     $thisfn=~s/^priv\///;
1.1032    raeburn  13357:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13358:         $thisfn=~s/\?.+$//;
                   13359:     }
1.268     www      13360:     return $thisfn;
                   13361: }
                   13362: 
                   13363: # ------------------------------------------------------------- Clutter up URLs
                   13364: 
                   13365: sub clutter {
                   13366:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13367:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13368: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13369:        $thisfn='/res'.$thisfn; 
                   13370:     }
1.1031    raeburn  13371:     if ($thisfn !~m|^/adm|) {
                   13372: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13373: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13374: 	} else {
                   13375: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13376: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13377: 	    if ($embstyle eq 'ssi'
                   13378: 		|| ($embstyle eq 'hdn')
                   13379: 		|| ($embstyle eq 'rat')
                   13380: 		|| ($embstyle eq 'prv')
                   13381: 		|| ($embstyle eq 'ign')) {
                   13382: 		#do nothing with these
                   13383: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13384: 		|| ($embstyle eq 'emb')
                   13385: 		|| ($embstyle eq 'wrp')) {
                   13386: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13387: 	    } elsif ($embstyle eq 'unk'
                   13388: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13389: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13390: 	    } else {
1.718     www      13391: #		&logthis("Got a blank emb style");
1.695     albertel 13392: 	    }
1.694     albertel 13393: 	}
                   13394:     }
1.31      www      13395:     return $thisfn;
1.12      www      13396: }
                   13397: 
1.787     albertel 13398: sub clutter_with_no_wrapper {
                   13399:     my $uri = &clutter(shift);
                   13400:     if ($uri =~ m-^/adm/-) {
                   13401: 	$uri =~ s-^/adm/wrapper/-/-;
                   13402: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13403:     }
                   13404:     return $uri;
                   13405: }
                   13406: 
1.557     albertel 13407: sub freeze_escape {
                   13408:     my ($value)=@_;
                   13409:     if (ref($value)) {
                   13410: 	$value=&nfreeze($value);
                   13411: 	return '__FROZEN__'.&escape($value);
                   13412:     }
                   13413:     return &escape($value);
                   13414: }
                   13415: 
1.11      www      13416: 
1.557     albertel 13417: sub thaw_unescape {
                   13418:     my ($value)=@_;
                   13419:     if ($value =~ /^__FROZEN__/) {
                   13420: 	substr($value,0,10,undef);
                   13421: 	$value=&unescape($value);
                   13422: 	return &thaw($value);
                   13423:     }
                   13424:     return &unescape($value);
                   13425: }
                   13426: 
1.436     albertel 13427: sub correct_line_ends {
                   13428:     my ($result)=@_;
                   13429:     $$result =~s/\r\n/\n/mg;
                   13430:     $$result =~s/\r/\n/mg;
1.415     albertel 13431: }
1.1       albertel 13432: # ================================================================ Main Program
                   13433: 
1.184     www      13434: sub goodbye {
1.204     albertel 13435:    &logthis("Starting Shut down");
1.443     albertel 13436: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13437:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13438: #converted
1.599     albertel 13439: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13440:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13441: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13442: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13443: #1.1 only
1.870     albertel 13444: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13445: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13446: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13447: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13448:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13449:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13450:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13451:    &flushcourselogs();
                   13452:    &logthis("Shutting down");
                   13453: }
                   13454: 
1.852     albertel 13455: sub get_dns {
1.1172.2.17  raeburn  13456:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13457:     if (!$ignore_cache) {
                   13458: 	my ($content,$cached)=
                   13459: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13460: 	if ($cached) {
1.1172.2.17  raeburn  13461: 	    &$func($content,$hashref);
1.869     albertel 13462: 	    return;
                   13463: 	}
                   13464:     }
                   13465: 
                   13466:     my %alldns;
1.1172.2.96  raeburn  13467:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13468:         foreach my $dns (<$config>) {
                   13469: 	    next if ($dns !~ /^\^(\S*)/x);
                   13470:             my $line = $1;
                   13471:             my ($host,$protocol) = split(/:/,$line);
                   13472:             if ($protocol ne 'https') {
                   13473:                 $protocol = 'http';
                   13474:             }
                   13475: 	    $alldns{$host} = $protocol;
1.979     raeburn  13476:         }
1.1172.2.96  raeburn  13477:         close($config);
1.869     albertel 13478:     }
                   13479:     while (%alldns) {
1.1172.2.52  raeburn  13480: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13481: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13482:         $ua->timeout(30);
1.979     raeburn  13483: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13484: 	my $response=$ua->request($request);
1.979     raeburn  13485:         delete($alldns{$dns});
1.852     albertel 13486: 	next if ($response->is_error());
                   13487: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13488:         unless ($nocache) {
1.1172.2.23  raeburn  13489: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13490:         }
                   13491: 	&$func(\@content,$hashref);
1.869     albertel 13492: 	return;
1.852     albertel 13493:     }
1.871     albertel 13494:     my $which = (split('/',$url))[3];
                   13495:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13496:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13497:         my @content = <$config>;
                   13498:         &$func(\@content,$hashref);
                   13499:     }
1.1172.2.17  raeburn  13500:     return;
                   13501: }
                   13502: 
                   13503: # ------------------------------------------------------Get DNS checksums file
                   13504: sub parse_dns_checksums_tab {
                   13505:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13506:     my $lonhost = $perlvar{'lonHostID'};
                   13507:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13508:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13509:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13510:     my $webconfdir = '/etc/httpd/conf';
                   13511:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13512:         $webconfdir = '/etc/apache2';
                   13513:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13514:         if ($1 >= 10) {
                   13515:             $webconfdir = '/etc/apache2';
                   13516:         }
                   13517:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13518:         if ($1 >= 10.0) {
                   13519:             $webconfdir = '/etc/apache2';
                   13520:         }
                   13521:     }
1.1172.2.17  raeburn  13522:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13523:     my (%chksum,%revnum);
                   13524:     if (ref($lines) eq 'ARRAY') {
                   13525:         chomp(@{$lines});
1.1172.2.34  raeburn  13526:         my $version = shift(@{$lines});
                   13527:         if ($version eq $release) {
1.1172.2.17  raeburn  13528:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13529:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13530:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13531:                     if ($webconfdir eq '/etc/apache2') {
                   13532:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13533:                     }
                   13534:                 }
1.1172.2.34  raeburn  13535:                 $chksum{$file} = $shasum;
                   13536:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13537:             }
                   13538:             if (ref($hashref) eq 'HASH') {
                   13539:                 %{$hashref} = (
                   13540:                                 sums     => \%chksum,
                   13541:                                 versions => \%revnum,
                   13542:                               );
                   13543:             }
                   13544:         }
                   13545:     }
1.869     albertel 13546:     return;
1.852     albertel 13547: }
1.1172.2.17  raeburn  13548: 
                   13549: sub fetch_dns_checksums {
                   13550:     my %checksums;
1.1172.2.34  raeburn  13551:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13552:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13553:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13554:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13555:              \%checksums);
                   13556:     return \%checksums;
                   13557: }
                   13558: 
1.327     albertel 13559: # ------------------------------------------------------------ Read domain file
                   13560: {
1.852     albertel 13561:     my $loaded;
1.846     albertel 13562:     my %domain;
                   13563: 
1.852     albertel 13564:     sub parse_domain_tab {
                   13565: 	my ($lines) = @_;
                   13566: 	foreach my $line (@$lines) {
                   13567: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13568: 
1.846     albertel 13569: 	    chomp($line);
1.852     albertel 13570: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13571: 	    my %this_domain;
                   13572: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13573: 			       'lang_def', 'city', 'longi', 'lati',
                   13574: 			       'primary') {
                   13575: 		$this_domain{$field} = shift(@elements);
                   13576: 	    }
                   13577: 	    $domain{$name} = \%this_domain;
1.852     albertel 13578: 	}
                   13579:     }
1.864     albertel 13580: 
                   13581:     sub reset_domain_info {
                   13582: 	undef($loaded);
                   13583: 	undef(%domain);
                   13584:     }
                   13585: 
1.852     albertel 13586:     sub load_domain_tab {
1.1172.2.70  raeburn  13587: 	my ($ignore_cache,$nocache) = @_;
                   13588: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13589: 	my $fh;
1.1172.2.96  raeburn  13590: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13591: 	    my @lines = <$fh>;
                   13592: 	    &parse_domain_tab(\@lines);
1.448     albertel 13593: 	}
1.852     albertel 13594: 	close($fh);
                   13595: 	$loaded = 1;
1.327     albertel 13596:     }
1.846     albertel 13597: 
                   13598:     sub domain {
1.852     albertel 13599: 	&load_domain_tab() if (!$loaded);
                   13600: 
1.846     albertel 13601: 	my ($name,$what) = @_;
                   13602: 	return if ( !exists($domain{$name}) );
                   13603: 
                   13604: 	if (!$what) {
                   13605: 	    return $domain{$name}{'description'};
                   13606: 	}
                   13607: 	return $domain{$name}{$what};
                   13608:     }
1.974     raeburn  13609: 
                   13610:     sub domain_info {
                   13611:         &load_domain_tab() if (!$loaded);
                   13612:         return %domain;
                   13613:     }
                   13614: 
1.327     albertel 13615: }
                   13616: 
                   13617: 
1.1       albertel 13618: # ------------------------------------------------------------- Read hosts file
                   13619: {
1.838     albertel 13620:     my %hostname;
1.844     albertel 13621:     my %hostdom;
1.845     albertel 13622:     my %libserv;
1.852     albertel 13623:     my $loaded;
1.888     albertel 13624:     my %name_to_host;
1.1074    raeburn  13625:     my %internetdom;
1.1107    raeburn  13626:     my %LC_dns_serv;
1.852     albertel 13627: 
                   13628:     sub parse_hosts_tab {
                   13629: 	my ($file) = @_;
                   13630: 	foreach my $configline (@$file) {
                   13631: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13632:             chomp($configline);
                   13633: 	    if ($configline =~ /^\^/) {
                   13634:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13635:                     $LC_dns_serv{$1} = 1;
                   13636:                 }
                   13637:                 next;
                   13638:             }
1.1074    raeburn  13639: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13640: 	    $name=~s/\s//g;
                   13641: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13642:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13643:                     my $curr = $hostname{$id};
                   13644:                     my $skip;
                   13645:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13646:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13647:                             $skip = 1;
                   13648:                         } else {
                   13649:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13650:                         }
                   13651:                     }
                   13652:                     unless ($skip) {
                   13653:                         push(@{$name_to_host{$name}},$id);
                   13654:                     }
                   13655:                 } else {
                   13656:                     push(@{$name_to_host{$name}},$id);
                   13657:                 }
1.852     albertel 13658: 		$hostname{$id}=$name;
                   13659: 		$hostdom{$id}=$domain;
                   13660: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13661:                 if (defined($protocol)) {
                   13662:                     if ($protocol eq 'https') {
                   13663:                         $protocol{$id} = $protocol;
                   13664:                     } else {
                   13665:                         $protocol{$id} = 'http'; 
                   13666:                     }
1.968     raeburn  13667:                 } else {
1.969     raeburn  13668:                     $protocol{$id} = 'http';
1.968     raeburn  13669:                 }
1.1074    raeburn  13670:                 if (defined($intdom)) {
                   13671:                     $internetdom{$id} = $intdom;
                   13672:                 }
1.852     albertel 13673: 	    }
                   13674: 	}
                   13675:     }
1.864     albertel 13676:     
                   13677:     sub reset_hosts_info {
1.897     albertel 13678: 	&purge_remembered();
1.864     albertel 13679: 	&reset_domain_info();
                   13680: 	&reset_hosts_ip_info();
1.892     albertel 13681: 	undef(%name_to_host);
1.864     albertel 13682: 	undef(%hostname);
                   13683: 	undef(%hostdom);
                   13684: 	undef(%libserv);
                   13685: 	undef($loaded);
                   13686:     }
1.1       albertel 13687: 
1.852     albertel 13688:     sub load_hosts_tab {
1.1172.2.70  raeburn  13689: 	my ($ignore_cache,$nocache) = @_;
                   13690: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13691: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13692: 	my @config = <$config>;
                   13693: 	&parse_hosts_tab(\@config);
                   13694: 	close($config);
                   13695: 	$loaded=1;
1.1       albertel 13696:     }
1.852     albertel 13697: 
1.838     albertel 13698:     sub hostname {
1.852     albertel 13699: 	&load_hosts_tab() if (!$loaded);
                   13700: 
1.838     albertel 13701: 	my ($lonid) = @_;
                   13702: 	return $hostname{$lonid};
                   13703:     }
1.845     albertel 13704: 
1.838     albertel 13705:     sub all_hostnames {
1.852     albertel 13706: 	&load_hosts_tab() if (!$loaded);
                   13707: 
1.838     albertel 13708: 	return %hostname;
                   13709:     }
1.845     albertel 13710: 
1.888     albertel 13711:     sub all_names {
1.1172.2.70  raeburn  13712:         my ($ignore_cache,$nocache) = @_;
                   13713: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13714: 
                   13715: 	return %name_to_host;
                   13716:     }
                   13717: 
1.974     raeburn  13718:     sub all_host_domain {
                   13719:         &load_hosts_tab() if (!$loaded);
                   13720:         return %hostdom;
                   13721:     }
                   13722: 
1.845     albertel 13723:     sub is_library {
1.852     albertel 13724: 	&load_hosts_tab() if (!$loaded);
                   13725: 
1.845     albertel 13726: 	return exists($libserv{$_[0]});
                   13727:     }
                   13728: 
                   13729:     sub all_library {
1.852     albertel 13730: 	&load_hosts_tab() if (!$loaded);
                   13731: 
1.845     albertel 13732: 	return %libserv;
                   13733:     }
                   13734: 
1.1062    droeschl 13735:     sub unique_library {
                   13736: 	#2x reverse removes all hostnames that appear more than once
                   13737:         my %unique = reverse &all_library();
                   13738:         return reverse %unique;
                   13739:     }
                   13740: 
1.841     albertel 13741:     sub get_servers {
1.852     albertel 13742: 	&load_hosts_tab() if (!$loaded);
                   13743: 
1.841     albertel 13744: 	my ($domain,$type) = @_;
                   13745: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13746: 	                                          : %hostname;
                   13747: 	my %result;
1.842     albertel 13748: 	if (ref($domain) eq 'ARRAY') {
                   13749: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13750: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13751: 		    $result{$host} = $hostname;
                   13752: 		}
                   13753: 	    }
                   13754: 	} else {
                   13755: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13756: 		if ($hostdom{$host} eq $domain) {
                   13757: 		    $result{$host} = $hostname;
                   13758: 		}
1.841     albertel 13759: 	    }
                   13760: 	}
                   13761: 	return %result;
                   13762:     }
1.845     albertel 13763: 
1.1062    droeschl 13764:     sub get_unique_servers {
                   13765:         my %unique = reverse &get_servers(@_);
                   13766: 	return reverse %unique;
                   13767:     }
                   13768: 
1.844     albertel 13769:     sub host_domain {
1.852     albertel 13770: 	&load_hosts_tab() if (!$loaded);
                   13771: 
1.844     albertel 13772: 	my ($lonid) = @_;
                   13773: 	return $hostdom{$lonid};
                   13774:     }
                   13775: 
1.841     albertel 13776:     sub all_domains {
1.852     albertel 13777: 	&load_hosts_tab() if (!$loaded);
                   13778: 
1.841     albertel 13779: 	my %seen;
                   13780: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13781: 	return @uniq;
                   13782:     }
1.1074    raeburn  13783: 
                   13784:     sub internet_dom {
                   13785:         &load_hosts_tab() if (!$loaded);
                   13786: 
                   13787:         my ($lonid) = @_;
                   13788:         return $internetdom{$lonid};
                   13789:     }
1.1107    raeburn  13790: 
                   13791:     sub is_LC_dns {
                   13792:         &load_hosts_tab() if (!$loaded);
                   13793: 
                   13794:         my ($hostname) = @_;
                   13795:         return exists($LC_dns_serv{$hostname});
                   13796:     }
                   13797: 
1.1       albertel 13798: }
                   13799: 
1.847     albertel 13800: { 
                   13801:     my %iphost;
1.856     albertel 13802:     my %name_to_ip;
                   13803:     my %lonid_to_ip;
1.869     albertel 13804: 
1.847     albertel 13805:     sub get_hosts_from_ip {
                   13806: 	my ($ip) = @_;
                   13807: 	my %iphosts = &get_iphost();
                   13808: 	if (ref($iphosts{$ip})) {
                   13809: 	    return @{$iphosts{$ip}};
                   13810: 	}
                   13811: 	return;
1.839     albertel 13812:     }
1.864     albertel 13813:     
                   13814:     sub reset_hosts_ip_info {
                   13815: 	undef(%iphost);
                   13816: 	undef(%name_to_ip);
                   13817: 	undef(%lonid_to_ip);
                   13818:     }
1.856     albertel 13819: 
                   13820:     sub get_host_ip {
                   13821: 	my ($lonid) = @_;
                   13822: 	if (exists($lonid_to_ip{$lonid})) {
                   13823: 	    return $lonid_to_ip{$lonid};
                   13824: 	}
                   13825: 	my $name=&hostname($lonid);
                   13826:    	my $ip = gethostbyname($name);
                   13827: 	return if (!$ip || length($ip) ne 4);
                   13828: 	$ip=inet_ntoa($ip);
                   13829: 	$name_to_ip{$name}   = $ip;
                   13830: 	$lonid_to_ip{$lonid} = $ip;
                   13831: 	return $ip;
                   13832:     }
1.847     albertel 13833:     
                   13834:     sub get_iphost {
1.1172.2.70  raeburn  13835: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13836: 
1.869     albertel 13837: 	if (!$ignore_cache) {
                   13838: 	    if (%iphost) {
                   13839: 		return %iphost;
                   13840: 	    }
                   13841: 	    my ($ip_info,$cached)=
                   13842: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13843: 	    if ($cached) {
                   13844: 		%iphost      = %{$ip_info->[0]};
                   13845: 		%name_to_ip  = %{$ip_info->[1]};
                   13846: 		%lonid_to_ip = %{$ip_info->[2]};
                   13847: 		return %iphost;
                   13848: 	    }
                   13849: 	}
1.894     albertel 13850: 
                   13851: 	# get yesterday's info for fallback
                   13852: 	my %old_name_to_ip;
                   13853: 	my ($ip_info,$cached)=
                   13854: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13855: 	if ($cached) {
                   13856: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13857: 	}
                   13858: 
1.1172.2.70  raeburn  13859: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13860: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13861: 	    my $ip;
                   13862: 	    if (!exists($name_to_ip{$name})) {
                   13863: 		$ip = gethostbyname($name);
                   13864: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13865: 		    if (defined($old_name_to_ip{$name})) {
                   13866: 			$ip = $old_name_to_ip{$name};
                   13867: 			&logthis("Can't find $name defaulting to old $ip");
                   13868: 		    } else {
                   13869: 			&logthis("Name $name no IP found");
                   13870: 			next;
                   13871: 		    }
                   13872: 		} else {
                   13873: 		    $ip=inet_ntoa($ip);
1.847     albertel 13874: 		}
                   13875: 		$name_to_ip{$name} = $ip;
                   13876: 	    } else {
                   13877: 		$ip = $name_to_ip{$name};
1.653     albertel 13878: 	    }
1.888     albertel 13879: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13880: 		$lonid_to_ip{$id} = $ip;
                   13881: 	    }
                   13882: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13883: 	}
1.1172.2.70  raeburn  13884:         unless ($nocache) {
                   13885: 	    &do_cache_new('iphost','iphost',
                   13886: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13887: 		          48*60*60);
                   13888:         }
1.869     albertel 13889: 
1.847     albertel 13890: 	return %iphost;
1.598     albertel 13891:     }
                   13892: 
1.992     raeburn  13893:     #
                   13894:     #  Given a DNS returns the loncapa host name for that DNS 
                   13895:     # 
                   13896:     sub host_from_dns {
                   13897:         my ($dns) = @_;
                   13898:         my @hosts;
                   13899:         my $ip;
                   13900: 
1.993     raeburn  13901:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13902:             $ip = $name_to_ip{$dns};
                   13903:         }
                   13904:         if (!$ip) {
                   13905:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13906:             if (length($ip) == 4) { 
                   13907: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13908:             }
                   13909:         }
                   13910:         if ($ip) {
                   13911: 	    @hosts = get_hosts_from_ip($ip);
                   13912: 	    return $hosts[0];
                   13913:         }
                   13914:         return undef;
1.986     foxr     13915:     }
1.992     raeburn  13916: 
1.1074    raeburn  13917:     sub get_internet_names {
                   13918:         my ($lonid) = @_;
                   13919:         return if ($lonid eq '');
                   13920:         my ($idnref,$cached)=
                   13921:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13922:         if ($cached) {
                   13923:             return $idnref;
                   13924:         }
                   13925:         my $ip = &get_host_ip($lonid);
                   13926:         my @hosts = &get_hosts_from_ip($ip);
                   13927:         my %iphost = &get_iphost();
                   13928:         my (@idns,%seen);
                   13929:         foreach my $id (@hosts) {
                   13930:             my $dom = &host_domain($id);
                   13931:             my $prim_id = &domain($dom,'primary');
                   13932:             my $prim_ip = &get_host_ip($prim_id);
                   13933:             next if ($seen{$prim_ip});
                   13934:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13935:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13936:                     my $intdom = &internet_dom($id);
                   13937:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13938:                         push(@idns,$intdom);
                   13939:                     }
                   13940:                 }
                   13941:             }
                   13942:             $seen{$prim_ip} = 1;
                   13943:         }
1.1172.2.23  raeburn  13944:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13945:     }
                   13946: 
1.986     foxr     13947: }
                   13948: 
1.1079    raeburn  13949: sub all_loncaparevs {
1.1172.2.39  raeburn  13950:     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  13951: }
                   13952: 
1.1172.2.27  raeburn  13953: # ------------------------------------------------------- Read loncaparev table
                   13954: {
                   13955:     sub load_loncaparevs {
                   13956:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13957:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13958:                 while (my $configline=<$config>) {
                   13959:                     chomp($configline);
                   13960:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13961:                     $loncaparevs{$hostid}=$loncaparev;
                   13962:                 }
                   13963:                 close($config);
                   13964:             }
                   13965:         }
                   13966:     }
                   13967: }
                   13968: 
                   13969: # ----------------------------------------------------- Read serverhostID table
                   13970: {
                   13971:     sub load_serverhomeIDs {
                   13972:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13973:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13974:                 while (my $configline=<$config>) {
                   13975:                     chomp($configline);
                   13976:                     my ($name,$id)=split(/:/,$configline);
                   13977:                     $serverhomeIDs{$name}=$id;
                   13978:                 }
                   13979:                 close($config);
                   13980:             }
                   13981:         }
                   13982:     }
                   13983: }
                   13984: 
                   13985: 
1.862     albertel 13986: BEGIN {
                   13987: 
                   13988: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13989:     unless ($readit) {
                   13990: {
                   13991:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13992:     %perlvar = (%perlvar,%{$configvars});
                   13993: }
                   13994: 
                   13995: 
1.1       albertel 13996: # ------------------------------------------------------ Read spare server file
                   13997: {
1.1172.2.96  raeburn  13998:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13999: 
                   14000:     while (my $configline=<$config>) {
                   14001:        chomp($configline);
1.284     matthew  14002:        if ($configline) {
1.784     albertel 14003: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14004: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14005: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14006:        }
                   14007:     }
1.448     albertel 14008:     close($config);
1.1       albertel 14009: }
1.11      www      14010: # ------------------------------------------------------------ Read permissions
                   14011: {
1.1172.2.96  raeburn  14012:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14013: 
                   14014:     while (my $configline=<$config>) {
1.448     albertel 14015: 	chomp($configline);
                   14016: 	if ($configline) {
                   14017: 	    my ($role,$perm)=split(/ /,$configline);
                   14018: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14019: 	}
1.11      www      14020:     }
1.448     albertel 14021:     close($config);
1.11      www      14022: }
                   14023: 
                   14024: # -------------------------------------------- Read plain texts for permissions
                   14025: {
1.1172.2.96  raeburn  14026:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14027: 
                   14028:     while (my $configline=<$config>) {
1.448     albertel 14029: 	chomp($configline);
                   14030: 	if ($configline) {
1.742     raeburn  14031: 	    my ($short,@plain)=split(/:/,$configline);
                   14032:             %{$prp{$short}} = ();
                   14033: 	    if (@plain > 0) {
                   14034:                 $prp{$short}{'std'} = $plain[0];
                   14035:                 for (my $i=1; $i<@plain; $i++) {
                   14036:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14037:                 }
                   14038:             }
1.448     albertel 14039: 	}
1.135     www      14040:     }
1.448     albertel 14041:     close($config);
1.135     www      14042: }
                   14043: 
                   14044: # ---------------------------------------------------------- Read package table
                   14045: {
1.1172.2.96  raeburn  14046:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14047: 
                   14048:     while (my $configline=<$config>) {
1.483     albertel 14049: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14050: 	chomp($configline);
                   14051: 	my ($short,$plain)=split(/:/,$configline);
                   14052: 	my ($pack,$name)=split(/\&/,$short);
                   14053: 	if ($plain ne '') {
                   14054: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14055: 	    $packagetab{$short}=$plain; 
                   14056: 	}
1.11      www      14057:     }
1.448     albertel 14058:     close($config);
1.329     matthew  14059: }
                   14060: 
1.1172.2.27  raeburn  14061: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14062: 
1.1172.2.27  raeburn  14063: &load_loncaparevs();
                   14064: 
                   14065: # ------------------------------------------------------- Read serverhostID table
                   14066: 
                   14067: &load_serverhomeIDs();
1.1074    raeburn  14068: 
1.1172.2.27  raeburn  14069: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14070: {
                   14071:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14072:     if (-e $file) {
                   14073:         my $parser = HTML::LCParser->new($file);
                   14074:         while (my $token = $parser->get_token()) {
                   14075:             if ($token->[0] eq 'S') {
                   14076:                 my $item = $token->[1];
                   14077:                 my $name = $token->[2]{'name'};
                   14078:                 my $value = $token->[2]{'value'};
                   14079:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14080:                     my $release = $parser->get_text();
                   14081:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14082:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14083:                 }
                   14084:             }
                   14085:         }
                   14086:     }
1.1073    raeburn  14087: }
                   14088: 
1.1138    raeburn  14089: # ---------------------------------------------------------- Read managers table
                   14090: {
                   14091:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14092:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14093:             while (my $configline=<$config>) {
                   14094:                 chomp($configline);
                   14095:                 next if ($configline =~ /^\#/);
                   14096:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14097:                     $managerstab{$configline} = 1;
                   14098:                 }
                   14099:             }
                   14100:             close($config);
                   14101:         }
                   14102:     }
                   14103: }
                   14104: 
1.329     matthew  14105: # ------------- set up temporary directory
                   14106: {
1.1117    foxr     14107:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14108: 
1.11      www      14109: }
                   14110: 
1.1172.2.104  raeburn  14111: # ------------- set default texengine (domain default overrides this)
                   14112: {
                   14113:     $deftex = LONCAPA::texengine();
                   14114: }
                   14115: 
1.1172.2.114  raeburn  14116: # ------------- set default minimum length for passwords for internal auth users
                   14117: {
                   14118:     $passwdmin = LONCAPA::passwd_min();
                   14119: }
                   14120: 
1.794     albertel 14121: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14122: 				'compress_threshold'=> 20_000,
                   14123:  			        });
1.185     www      14124: 
1.281     www      14125: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14126: $dumpcount=0;
1.958     www      14127: $locknum=0;
1.22      www      14128: 
1.163     harris41 14129: &logtouch();
1.672     albertel 14130: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14131: $readit=1;
1.564     albertel 14132:     {
                   14133: 	use integer;
                   14134: 	my $test=(2**32)+1;
1.568     albertel 14135: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14136: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14137:     }
1.195     www      14138: }
1.1       albertel 14139: }
1.179     www      14140: 
1.1       albertel 14141: 1;
1.191     harris41 14142: __END__
                   14143: 
1.243     albertel 14144: =pod
                   14145: 
1.191     harris41 14146: =head1 NAME
                   14147: 
1.243     albertel 14148: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14149: 
                   14150: =head1 SYNOPSIS
                   14151: 
1.243     albertel 14152: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14153: 
                   14154:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14155: 
1.243     albertel 14156: Common parameters:
                   14157: 
                   14158: =over 4
                   14159: 
                   14160: =item *
                   14161: 
                   14162: $uname : an internal username (if $cname expecting a course Id specifically)
                   14163: 
                   14164: =item *
                   14165: 
                   14166: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14167: 
                   14168: =item *
                   14169: 
                   14170: $symb : a resource instance identifier
                   14171: 
                   14172: =item *
                   14173: 
                   14174: $namespace : the name of a .db file that contains the data needed or
                   14175: being set.
                   14176: 
                   14177: =back
                   14178: 
1.394     bowersj2 14179: =head1 OVERVIEW
1.191     harris41 14180: 
1.394     bowersj2 14181: lonnet provides subroutines which interact with the
                   14182: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14183: about classes, users, and resources.
1.243     albertel 14184: 
                   14185: For many of these objects you can also use this to store data about
                   14186: them or modify them in various ways.
1.191     harris41 14187: 
1.394     bowersj2 14188: =head2 Symbs
1.191     harris41 14189: 
1.394     bowersj2 14190: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14191: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14192: map, the resource number of the resource in the map, and the URL of
                   14193: the resource itself. The latter is somewhat redundant, but might help
                   14194: if maps change.
                   14195: 
                   14196: An example is
                   14197: 
                   14198:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14199: 
                   14200: The respective map entry is
                   14201: 
                   14202:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14203:   title="Problem 2">
                   14204:  </resource>
                   14205: 
                   14206: Symbs are used by the random number generator, as well as to store and
                   14207: restore data specific to a certain instance of for example a problem.
                   14208: 
                   14209: =head2 Storing And Retrieving Data
                   14210: 
                   14211: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14212: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14213: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14214: is is the non-critical message twin of cstore. These functions are for
                   14215: handlers to store a perl hash to a user's permanent data space in an
                   14216: easy manner, and to retrieve it again on another call. It is expected
                   14217: that a handler would use this once at the beginning to retrieve data,
                   14218: and then again once at the end to send only the new data back.
                   14219: 
                   14220: The data is stored in the user's data directory on the user's
                   14221: homeserver under the ID of the course.
                   14222: 
                   14223: The hash that is returned by restore will have all of the previous
                   14224: value for all of the elements of the hash.
                   14225: 
                   14226: Example:
                   14227: 
                   14228:  #creating a hash
                   14229:  my %hash;
                   14230:  $hash{'foo'}='bar';
                   14231: 
                   14232:  #storing it
                   14233:  &Apache::lonnet::cstore(\%hash);
                   14234: 
                   14235:  #changing a value
                   14236:  $hash{'foo'}='notbar';
                   14237: 
                   14238:  #adding a new value
                   14239:  $hash{'bar'}='foo';
                   14240:  &Apache::lonnet::cstore(\%hash);
                   14241: 
                   14242:  #retrieving the hash
                   14243:  my %history=&Apache::lonnet::restore();
                   14244: 
                   14245:  #print the hash
                   14246:  foreach my $key (sort(keys(%history))) {
                   14247:    print("\%history{$key} = $history{$key}");
                   14248:  }
                   14249: 
                   14250: Will print out:
1.191     harris41 14251: 
1.394     bowersj2 14252:  %history{1:foo} = bar
                   14253:  %history{1:keys} = foo:timestamp
                   14254:  %history{1:timestamp} = 990455579
                   14255:  %history{2:bar} = foo
                   14256:  %history{2:foo} = notbar
                   14257:  %history{2:keys} = foo:bar:timestamp
                   14258:  %history{2:timestamp} = 990455580
                   14259:  %history{bar} = foo
                   14260:  %history{foo} = notbar
                   14261:  %history{timestamp} = 990455580
                   14262:  %history{version} = 2
                   14263: 
                   14264: Note that the special hash entries C<keys>, C<version> and
                   14265: C<timestamp> were added to the hash. C<version> will be equal to the
                   14266: total number of versions of the data that have been stored. The
                   14267: C<timestamp> attribute will be the UNIX time the hash was
                   14268: stored. C<keys> is available in every historical section to list which
                   14269: keys were added or changed at a specific historical revision of a
                   14270: hash.
                   14271: 
                   14272: B<Warning>: do not store the hash that restore returns directly. This
                   14273: will cause a mess since it will restore the historical keys as if the
                   14274: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14275: 
1.394     bowersj2 14276: Calling convention:
1.191     harris41 14277: 
1.1172.2.27  raeburn  14278:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14279:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14280: 
1.394     bowersj2 14281: For more detailed information, see lonnet specific documentation.
1.191     harris41 14282: 
1.394     bowersj2 14283: =head1 RETURN MESSAGES
1.191     harris41 14284: 
1.394     bowersj2 14285: =over 4
1.191     harris41 14286: 
1.394     bowersj2 14287: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14288: 
1.394     bowersj2 14289: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14290: when the connection is brought back up
1.191     harris41 14291: 
1.394     bowersj2 14292: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14293: for later delivery
1.191     harris41 14294: 
1.967     bisitz   14295: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14296: 
1.394     bowersj2 14297: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14298: that was requested
1.191     harris41 14299: 
1.243     albertel 14300: =back
1.191     harris41 14301: 
1.243     albertel 14302: =head1 PUBLIC SUBROUTINES
1.191     harris41 14303: 
1.243     albertel 14304: =head2 Session Environment Functions
1.191     harris41 14305: 
1.243     albertel 14306: =over 4
1.191     harris41 14307: 
1.394     bowersj2 14308: =item * 
                   14309: X<appenv()>
1.949     raeburn  14310: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14311: the user envirnoment file, and will be restored for each access this
1.620     albertel 14312: user makes during this session, also modifies the %env for the current
1.949     raeburn  14313: process. Optional rolesarrayref - if defined contains a reference to an array
                   14314: of roles which are exempt from the restriction on modifying user.role entries 
                   14315: in the user's environment.db and in %env.    
1.191     harris41 14316: 
                   14317: =item *
1.394     bowersj2 14318: X<delenv()>
1.987     raeburn  14319: B<delenv($delthis,$regexp)>: removes all items from the session
                   14320: environment file that begin with $delthis. If the 
                   14321: optional second arg - $regexp - is true, $delthis is treated as a 
                   14322: regular expression, otherwise \Q$delthis\E is used. 
                   14323: The values are also deleted from the current processes %env.
1.191     harris41 14324: 
1.795     albertel 14325: =item * get_env_multiple($name) 
                   14326: 
                   14327: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14328: values may be defined and end up as an array ref.
                   14329: 
                   14330: returns an array of values
                   14331: 
1.243     albertel 14332: =back
                   14333: 
                   14334: =head2 User Information
1.191     harris41 14335: 
1.243     albertel 14336: =over 4
1.191     harris41 14337: 
                   14338: =item *
1.394     bowersj2 14339: X<queryauthenticate()>
                   14340: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14341: authentication scheme
                   14342: 
                   14343: =item *
1.394     bowersj2 14344: X<authenticate()>
1.1073    raeburn  14345: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14346: authenticate user from domain's lib servers (first use the current
                   14347: one). C<$upass> should be the users password.
1.1073    raeburn  14348: $checkdefauth is optional (value is 1 if a check should be made to
                   14349:    authenticate user using default authentication method, and allow
                   14350:    account creation if username does not have account in the domain).
                   14351: $clientcancheckhost is optional (value is 1 if checking whether the
                   14352:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14353: 
                   14354: =item *
1.394     bowersj2 14355: X<homeserver()>
                   14356: B<homeserver($uname,$udom)>: find the server which has
                   14357: the user's directory and files (there must be only one), this caches
                   14358: the answer, and also caches if there is a borken connection.
1.191     harris41 14359: 
                   14360: =item *
1.394     bowersj2 14361: X<idget()>
                   14362: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14363: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14364: username, and only 1 username per ID in a specific domain) (returns
                   14365: hash: id=>name,id=>name)
1.191     harris41 14366: 
                   14367: =item *
1.394     bowersj2 14368: X<idrget()>
                   14369: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14370: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14371: 
                   14372: =item *
1.394     bowersj2 14373: X<idput()>
                   14374: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14375: 
                   14376: =item *
1.394     bowersj2 14377: X<rolesinit()>
1.1169    droeschl 14378: B<rolesinit($udom,$username)>: get user privileges.
                   14379: returns user role, first access and timer interval hashes
1.243     albertel 14380: 
                   14381: =item *
1.1171    droeschl 14382: X<privileged()>
                   14383: B<privileged($username,$domain)>: returns a true if user has a
                   14384: privileged and active role (i.e. su or dc), false otherwise.
                   14385: 
                   14386: =item *
1.551     albertel 14387: X<getsection()>
                   14388: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14389: course $cname, return section name/number or '' for "not in course"
                   14390: and '-1' for "no section"
                   14391: 
                   14392: =item *
1.394     bowersj2 14393: X<userenvironment()>
                   14394: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14395: passed in @what from the requested user's environment, returns a hash
                   14396: 
1.858     raeburn  14397: =item * 
                   14398: X<userlog_query()>
1.859     albertel 14399: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14400: activity.log file. %filters defines filters applied when parsing the
                   14401: log file. These can be start or end timestamps, or the type of action
                   14402: - log to look for Login or Logout events, check for Checkin or
                   14403: Checkout, role for role selection. The response is in the form
                   14404: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14405: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14406: 
1.243     albertel 14407: =back
                   14408: 
                   14409: =head2 User Roles
                   14410: 
                   14411: =over 4
                   14412: 
                   14413: =item *
                   14414: 
1.1172.2.65  raeburn  14415: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14416: returns codes for allowed actions.
                   14417: 
                   14418: The first argument is required, all others are optional.
                   14419: 
                   14420: $priv is the privilege being checked.
                   14421: $uri contains additional information about what is being checked for access (e.g.,
                   14422: URL, course ID etc.).
                   14423: $symb is the unique resource instance identifier in a course; if needed,
                   14424: but not provided, it will be retrieved via a call to &symbread().
                   14425: $role is the role for which a priv is being checked (only used if priv is evb).
                   14426: $clientip is the user's IP address (only used when checking for access to portfolio
                   14427: files).
                   14428: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14429: prevents recursive calls to &allowed.
                   14430: 
1.243     albertel 14431:  F: full access
                   14432:  U,I,K: authentication modes (cxx only)
                   14433:  '': forbidden
                   14434:  1: user needs to choose course
                   14435:  2: browse allowed
1.766     albertel 14436:  A: passphrase authentication needed
1.1172.2.65  raeburn  14437:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14438: 
                   14439: =item *
                   14440: 
1.1172.2.13  raeburn  14441: constructaccess($url,$setpriv) : check for access to construction space URL
                   14442: 
                   14443: See if the owner domain and name in the URL match those in the
                   14444: expected environment.  If so, return three element list
                   14445: ($ownername,$ownerdomain,$ownerhome).
                   14446: 
                   14447: Otherwise return the null string.
                   14448: 
                   14449: If second argument 'setpriv' is true, it assigns the privileges,
                   14450: and returns the same three element list, unless the owner has
                   14451: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14452: in which case the null string is returned.
                   14453: 
                   14454: =item *
                   14455: 
1.1172.2.84  raeburn  14456: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14457: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14458: for system, domain, and course level. $uname and $udom are optional (current
                   14459: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14460: 
                   14461: =item *
                   14462: 
1.988     raeburn  14463: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14464: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14465: $type is Course (default) or Community.
1.988     raeburn  14466: If $forcedefault evaluates to true, text returned will be default 
                   14467: text for $type. Otherwise, if this is a course, the text returned 
                   14468: will be a custom name for the role (if defined in the course's 
                   14469: environment).  If no custom name is defined the default is returned.
                   14470:    
1.832     raeburn  14471: =item *
                   14472: 
1.1172.2.23  raeburn  14473: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14474: All arguments are optional. Returns a hash of a roles, either for
                   14475: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14476: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14477: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14478: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14479: For each key, value is set to colon-separated start and end times for
                   14480: the role.  If no username and domain are specified, will default to
1.934     raeburn  14481: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14482: of role statuses (active, future or previous), roles 
                   14483: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14484: to restrict the list of roles reported. If no array ref is 
                   14485: provided for types, will default to return only active roles.
1.834     albertel 14486: 
1.1172.2.13  raeburn  14487: =item *
                   14488: 
                   14489: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14490: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14491: 
                   14492: Additional optional arguments are: $type (if role checking is to be restricted
                   14493: to certain user status types -- previous (expired roles), active (currently
                   14494: available roles) or future (roles available in the future), and
                   14495: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14496: have active Domain Coordinator role in course's domain or in additional
                   14497: domains (specified in 'Domains to check for privileged users' in course
                   14498: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14499: 
                   14500: =item *
                   14501: 
                   14502: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14503: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14504: $possdomains and $possroles are optional array refs -- to domains to check and
                   14505: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14506: users' roles.db to check for a dc or su role in any domain. This can be
                   14507: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14508: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14509: this then allows &privileged_by_domain() to be used, which caches the identity
                   14510: of privileged users, eliminating the need for repeated calls to &dump().
                   14511: 
                   14512: =item *
                   14513: 
                   14514: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14515: where the outer hash keys are domains specified in the $possdomains array ref,
                   14516: next inner hash keys are privileged roles specified in the $roles array ref,
                   14517: and the innermost hash contains key = value pairs for username:domain = end:start
                   14518: for active or future "privileged" users with that role in that domain. To avoid
                   14519: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14520: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14521: 
1.243     albertel 14522: =back
                   14523: 
                   14524: =head2 User Modification
                   14525: 
                   14526: =over 4
                   14527: 
                   14528: =item *
                   14529: 
1.957     raeburn  14530: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14531: user for the level given by URL.  Optional start and end dates (leave empty
                   14532: string or zero for "no date")
1.191     harris41 14533: 
                   14534: =item *
                   14535: 
1.243     albertel 14536: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14537: change a users, password, possible return values are: ok,
                   14538: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14539: refused
1.191     harris41 14540: 
                   14541: =item *
                   14542: 
1.243     albertel 14543: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14544: 
                   14545: =item *
                   14546: 
1.1058    raeburn  14547: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14548:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14549: 
                   14550: will update user information (firstname,middlename,lastname,generation,
                   14551: permanentemail), and if forceid is true, student/employee ID also.
                   14552: A user's institutional affiliation(s) can also be updated.
                   14553: User information fields will not be overwritten with empty entries 
                   14554: unless the field is included in the $candelete array reference.
                   14555: This array is included when a single user is modified via "Manage Users",
                   14556: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14557: 
                   14558: =item *
                   14559: 
1.286     matthew  14560: modifystudent
                   14561: 
1.957     raeburn  14562: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14563: The course id is resolved based on the current user's environment.  
                   14564: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14565: associated with a course.
                   14566: 
1.297     matthew  14567: This call is essentially a wrapper for lonnet::modifyuser and
                   14568: lonnet::modify_student_enrollment
1.286     matthew  14569: 
                   14570: Inputs: 
                   14571: 
                   14572: =over 4
                   14573: 
1.957     raeburn  14574: =item B<$udom> Student's loncapa domain
1.286     matthew  14575: 
1.957     raeburn  14576: =item B<$uname> Student's loncapa login name
1.286     matthew  14577: 
1.964     bisitz   14578: =item B<$uid> Student/Employee ID
1.286     matthew  14579: 
1.957     raeburn  14580: =item B<$umode> Student's authentication mode
1.286     matthew  14581: 
1.957     raeburn  14582: =item B<$upass> Student's password
1.286     matthew  14583: 
1.957     raeburn  14584: =item B<$first> Student's first name
1.286     matthew  14585: 
1.957     raeburn  14586: =item B<$middle> Student's middle name
1.286     matthew  14587: 
1.957     raeburn  14588: =item B<$last> Student's last name
1.286     matthew  14589: 
1.957     raeburn  14590: =item B<$gene> Student's generation
1.286     matthew  14591: 
1.957     raeburn  14592: =item B<$usec> Student's section in course
1.286     matthew  14593: 
                   14594: =item B<$end> Unix time of the roles expiration
                   14595: 
                   14596: =item B<$start> Unix time of the roles start date
                   14597: 
                   14598: =item B<$forceid> If defined, allow $uid to be changed
                   14599: 
                   14600: =item B<$desiredhome> server to use as home server for student
                   14601: 
1.957     raeburn  14602: =item B<$email> Student's permanent e-mail address
                   14603: 
                   14604: =item B<$type> Type of enrollment (auto or manual)
                   14605: 
1.963     raeburn  14606: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14607: 
                   14608: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14609: 
1.963     raeburn  14610: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14611: 
1.963     raeburn  14612: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14613: 
1.1172.2.19  raeburn  14614: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14615: 
                   14616: =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  14617: 
1.286     matthew  14618: =back
1.297     matthew  14619: 
                   14620: =item *
                   14621: 
                   14622: modify_student_enrollment
                   14623: 
1.1172.2.31  raeburn  14624: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14625: 'role.request.course' must be defined for this function to proceed.
                   14626: 
                   14627: Inputs:
                   14628: 
                   14629: =over 4
                   14630: 
1.1172.2.31  raeburn  14631: =item $udom, student's domain
1.297     matthew  14632: 
1.1172.2.31  raeburn  14633: =item $uname, student's name
1.297     matthew  14634: 
1.1172.2.31  raeburn  14635: =item $uid, student's user id
1.297     matthew  14636: 
1.1172.2.31  raeburn  14637: =item $first, student's first name
1.297     matthew  14638: 
                   14639: =item $middle
                   14640: 
                   14641: =item $last
                   14642: 
                   14643: =item $gene
                   14644: 
                   14645: =item $usec
                   14646: 
                   14647: =item $end
                   14648: 
                   14649: =item $start
                   14650: 
1.957     raeburn  14651: =item $type
                   14652: 
                   14653: =item $locktype
                   14654: 
                   14655: =item $cid
                   14656: 
                   14657: =item $selfenroll
                   14658: 
                   14659: =item $context
                   14660: 
1.1172.2.19  raeburn  14661: =item $credits, number of credits student will earn from this class
                   14662: 
1.1172.2.76  raeburn  14663: =item $instsec, institutional course section code for student
                   14664: 
1.297     matthew  14665: =back
                   14666: 
1.191     harris41 14667: 
                   14668: =item *
                   14669: 
1.243     albertel 14670: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14671: custom role; give a custom role to a user for the level given by URL.  Specify
                   14672: name and domain of role author, and role name
1.191     harris41 14673: 
                   14674: =item *
                   14675: 
1.243     albertel 14676: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14677: 
                   14678: =item *
                   14679: 
1.243     albertel 14680: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14681: 
                   14682: =back
                   14683: 
                   14684: =head2 Course Infomation
                   14685: 
                   14686: =over 4
1.191     harris41 14687: 
                   14688: =item *
                   14689: 
1.1118    foxr     14690: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14691: specified course id, including all environment settings for the
                   14692: course, the description of the course will be in the hash under the
                   14693: key 'description'
1.191     harris41 14694: 
1.1118    foxr     14695: $options is an optional parameter that if supplied is a hash reference that controls
                   14696: what how this function works.  It has the following key/values:
                   14697: 
                   14698: =over 4
                   14699: 
                   14700: =item freshen_cache
                   14701: 
                   14702: If defined, and the environment cache for the course is valid, it is 
                   14703: returned in the returned hash.
                   14704: 
                   14705: =item one_time
                   14706: 
                   14707: If defined, the last cache time is set to _now_
                   14708: 
                   14709: =item user
                   14710: 
                   14711: If defined, the supplied username is used instead of the current user.
                   14712: 
                   14713: 
                   14714: =back
                   14715: 
1.191     harris41 14716: =item *
                   14717: 
1.624     albertel 14718: resdata($name,$domain,$type,@which) : request for current parameter
                   14719: setting for a specific $type, where $type is either 'course' or 'user',
                   14720: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14721: answers for 10 minutes.
1.243     albertel 14722: 
1.877     foxr     14723: =item *
                   14724: 
                   14725: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14726: data base, returning a hash that is keyed by the resource name and has
                   14727: values that are the resource value.  I believe that the timestamps and
                   14728: versions are also returned.
                   14729: 
1.1172.2.31  raeburn  14730: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14731: supplemental content area. This routine caches the number of files for
                   14732: 10 minutes.
                   14733: 
1.243     albertel 14734: =back
                   14735: 
                   14736: =head2 Course Modification
                   14737: 
                   14738: =over 4
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.243     albertel 14742: writecoursepref($courseid,%prefs) : write preferences (environment
                   14743: database) for a course
1.191     harris41 14744: 
                   14745: =item *
                   14746: 
1.1011    raeburn  14747: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14748: 
                   14749: =item *
                   14750: 
1.1038    raeburn  14751: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14752: 
1.1167    droeschl 14753: =item *
                   14754: 
                   14755: is_course($courseid), is_course($cdom, $cnum)
                   14756: 
                   14757: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14758: two component version $cdom, $cnum. It checks if the specified course exists.
                   14759: 
                   14760: Returns:
                   14761:     undef if the course doesn't exist, otherwise
                   14762:     in scalar context the combined courseid.
                   14763:     in list context the two components of the course identifier, domain and 
                   14764:     courseid.    
                   14765: 
1.243     albertel 14766: =back
                   14767: 
1.1172.2.109  raeburn  14768: =head2 Bubblesheet Configuration
                   14769: 
                   14770: =over 4
                   14771: 
                   14772: =item *
                   14773: 
                   14774: get_scantron_config($which)
                   14775: 
                   14776: $which - the name of the configuration to parse from the file.
                   14777: 
                   14778: Parses and returns the bubblesheet configuration line selected as a
                   14779: hash of configuration file fields.
                   14780: 
                   14781: 
                   14782: Returns:
                   14783:     If the named configuration is not in the file, an empty
                   14784:     hash is returned.
                   14785: 
                   14786:     a hash with the fields
                   14787:       name         - internal name for the this configuration setup
                   14788:       description  - text to display to operator that describes this config
                   14789:       CODElocation - if 0 or the string 'none'
                   14790:                           - no CODE exists for this config
                   14791:                      if -1 || the string 'letter'
                   14792:                           - a CODE exists for this config and is
                   14793:                             a string of letters
                   14794:                      Unsupported value (but planned for future support)
                   14795:                           if a positive integer
                   14796:                                - The CODE exists as the first n items from
                   14797:                                  the question section of the form
                   14798:                           if the string 'number'
                   14799:                                - The CODE exists for this config and is
                   14800:                                  a string of numbers
                   14801:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14802:                      the CODE starts
                   14803:       CODElength  - length of the CODE
                   14804:       IDstart     - column where the student/employee ID starts
                   14805:       IDlength    - length of the student/employee ID info
                   14806:       Qstart      - column where the information from the bubbled
                   14807:                     'questions' start
                   14808:       Qlength     - number of columns comprising a single bubble line from
                   14809:                     the sheet. (usually either 1 or 10)
                   14810:       Qon         - either a single character representing the character used
                   14811:                     to signal a bubble was chosen in the positional setup, or
                   14812:                     the string 'letter' if the letter of the chosen bubble is
                   14813:                     in the final, or 'number' if a number representing the
                   14814:                     chosen bubble is in the file (1->A 0->J)
                   14815:       Qoff        - the character used to represent that a bubble was
                   14816:                     left blank
                   14817:       PaperID     - if the scanning process generates a unique number for each
                   14818:                     sheet scanned the column that this ID number starts in
                   14819:       PaperIDlength - number of columns that comprise the unique ID number
                   14820:                       for the sheet of paper
                   14821:       FirstName   - column that the first name starts in
                   14822:       FirstNameLength - number of columns that the first name spans
                   14823:       LastName    - column that the last name starts in
                   14824:       LastNameLength - number of columns that the last name spans
                   14825:       BubblesPerRow - number of bubbles available in each row used to
                   14826:                       bubble an answer. (If not specified, 10 assumed).
                   14827: 
                   14828: 
                   14829: =item *
                   14830: 
                   14831: get_scantronformat_file($cdom)
                   14832: 
                   14833: $cdom - the course's domain (optional); if not supplied, uses
                   14834: domain for current $env{'request.course.id'}.
                   14835: 
                   14836: Returns an array containing lines from the scantron format file for
                   14837: the domain of the course.
                   14838: 
                   14839: If a url for a custom.tab file is listed in domain's configuration.db,
                   14840: lines are from this file.
                   14841: 
                   14842: Otherwise, if a default.tab has been published in RES space by the
                   14843: domainconfig user, lines are from this file.
                   14844: 
                   14845: Otherwise, fall back to getting lines from the legacy file on the
                   14846: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14847: 
                   14848: =back
                   14849: 
1.243     albertel 14850: =head2 Resource Subroutines
                   14851: 
                   14852: =over 4
1.191     harris41 14853: 
                   14854: =item *
                   14855: 
1.243     albertel 14856: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: repcopy($filename) : subscribes to the requested file, and attempts to
                   14861: replicate from the owning library server, Might return
1.607     raeburn  14862: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14863: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14864: resource. Expects the local filesystem pathname
                   14865: (/home/httpd/html/res/....)
                   14866: 
                   14867: =back
                   14868: 
                   14869: =head2 Resource Information
                   14870: 
                   14871: =over 4
1.191     harris41 14872: 
                   14873: =item *
                   14874: 
1.1172.2.28  raeburn  14875: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14876: and returns the value of a variety of different possible values,
                   14877: $varname should be a request string, and the other parameters can be
                   14878: used to specify who and what one is asking about. Ordinarily, $cid 
                   14879: does not need to be specified, as it is retrived from 
                   14880: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14881: within lonuserstate::loadmap() when initializing a course, before
                   14882: $env{'request.course.id'} has been set, so it needs to be provided
                   14883: in that one case.
1.243     albertel 14884: 
                   14885: Possible values for $varname are environment.lastname (or other item
                   14886: from the envirnment hash), user.name (or someother aspect about the
                   14887: user), resource.0.maxtries (or some other part and parameter of a
                   14888: resource)
1.204     albertel 14889: 
                   14890: =item *
                   14891: 
1.243     albertel 14892: directcondval($number) : get current value of a condition; reads from a state
                   14893: string
1.204     albertel 14894: 
                   14895: =item *
                   14896: 
1.243     albertel 14897: condval($condidx) : value of condition index based on state
1.204     albertel 14898: 
                   14899: =item *
                   14900: 
1.243     albertel 14901: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14902: resource's metadata, $what should be either a specific key, or either
                   14903: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14904: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14905: 
                   14906: this function automatically caches all requests
1.191     harris41 14907: 
                   14908: =item *
                   14909: 
1.243     albertel 14910: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14911: network of library servers; returns file handle of where SQL and regex results
                   14912: will be stored for query
1.191     harris41 14913: 
                   14914: =item *
                   14915: 
1.1172.2.66  raeburn  14916: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14917: return symbolic list entry (all arguments optional).
                   14918: 
                   14919: Args: filename is the filename (including path) for the file for which a symb
                   14920: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14921: to check access status if more than one resource was found in the bighash
                   14922: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14923: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14924: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14925: cause possible symbs to be checked to determine if they are subject to content
                   14926: blocking, if so they will not be included as possible symbs; possibles is a
                   14927: ref to a hash, which, as a side effect, will be populated with all possible
                   14928: symbs (content blocking not tested).
                   14929: 
1.243     albertel 14930: returns the data handle
1.191     harris41 14931: 
                   14932: =item *
                   14933: 
1.1172.2.17  raeburn  14934: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14935: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14936: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14937: on failure, user must be in a course, as it assumes the existence of
                   14938: the course initial hash, and uses $env('request.course.id'}.  The third
                   14939: arg is an optional reference to a scalar.  If this arg is passed in the
                   14940: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14941: encrypted; otherwise it will be null.
1.243     albertel 14942: 
1.191     harris41 14943: =item *
                   14944: 
1.243     albertel 14945: symbclean($symb) : removes versions numbers from a symb, returns the
                   14946: cleaned symb
1.191     harris41 14947: 
                   14948: =item *
                   14949: 
1.243     albertel 14950: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14951: course map, user must be in a course for it to work.
1.191     harris41 14952: 
                   14953: =item *
                   14954: 
1.243     albertel 14955: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14956: 
                   14957: =item *
                   14958: 
1.243     albertel 14959: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14960: a random seed, all arguments are optional, if they aren't sent it uses the
                   14961: environment to derive them. Note: if symb isn't sent and it can't get one
                   14962: from &symbread it will use the current time as its return value
1.191     harris41 14963: 
                   14964: =item *
                   14965: 
1.243     albertel 14966: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14967: unfakeable, receipt
1.191     harris41 14968: 
                   14969: =item *
                   14970: 
1.620     albertel 14971: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14972: 
                   14973: =item *
                   14974: 
1.243     albertel 14975: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14976: 
                   14977: =item *
                   14978: 
1.243     albertel 14979: 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 14980: 
                   14981: =item *
                   14982: 
1.243     albertel 14983: 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 14984: 
                   14985: =item *
                   14986: 
1.243     albertel 14987: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14988: 
                   14989: =item *
                   14990: 
1.243     albertel 14991: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14992: forcing spreadsheet to reevaluate the resource scores next time.
                   14993: 
1.1172.2.13  raeburn  14994: =item *
                   14995: 
                   14996: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14997: when viewing in course context.
                   14998: 
                   14999:  input: six args -- filename (decluttered), course number, course domain,
                   15000:                     url, symb (if registered) and group (if this is a
                   15001:                     group item -- e.g., bulletin board, group page etc.).
                   15002: 
                   15003:  output: array of five scalars --
                   15004:          $cfile -- url for file editing if editable on current server
                   15005:          $home -- homeserver of resource (i.e., for author if published,
                   15006:                                           or course if uploaded.).
                   15007:          $switchserver --  1 if server switch will be needed.
                   15008:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15009:          $forceview -- 1 if icon/link should be to go to view mode
                   15010: 
                   15011: =item *
                   15012: 
                   15013: is_course_upload($file,$cnum,$cdom)
                   15014: 
                   15015: Used in course context to determine if current file was uploaded to
                   15016: the course (i.e., would be found in /userfiles/docs on the course's
                   15017: homeserver.
                   15018: 
                   15019:   input: 3 args -- filename (decluttered), course number and course domain.
                   15020:   output: boolean -- 1 if file was uploaded.
                   15021: 
1.243     albertel 15022: =back
                   15023: 
                   15024: =head2 Storing/Retreiving Data
                   15025: 
                   15026: =over 4
1.191     harris41 15027: 
                   15028: =item *
                   15029: 
1.1172.2.64  raeburn  15030: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15031: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15032: the remaining args aren't required and if they aren't passed or are '' they will
                   15033: be derived from the env (with the exception of $laststore, which is an
                   15034: optional arg used when a user's submission is stored in grading).
                   15035: $laststore is $version=$timestamp, where $version is the most recent version
                   15036: number retrieved for the corresponding $symb in the $namespace db file, and
                   15037: $timestamp is the timestamp for that transaction (UNIX time).
                   15038: $laststore is currently only passed when cstore() is called by
                   15039: structuretags::finalize_storage().
1.191     harris41 15040: 
                   15041: =item *
                   15042: 
1.1172.2.64  raeburn  15043: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15044: but uses critical subroutine
1.191     harris41 15045: 
                   15046: =item *
                   15047: 
1.243     albertel 15048: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15049: all args are optional
1.191     harris41 15050: 
                   15051: =item *
                   15052: 
1.717     albertel 15053: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15054: dumps the complete (or key matching regexp) namespace into a hash
                   15055: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15056: normally &store()ed into
                   15057: 
                   15058: $range should be either an integer '100' (give me the first 100
                   15059:                                            matching records)
                   15060:               or be  two integers sperated by a - with no spaces
                   15061:                  '30-50' (give me the 30th through the 50th matching
                   15062:                           records)
                   15063: 
                   15064: 
                   15065: =item *
                   15066: 
1.1172.2.59  raeburn  15067: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15068: replaces a &store() version of data with a replacement set of data
                   15069: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15070: reference. If $tolog is true, the transaction is logged in the courselog
                   15071: with an action=PUTSTORE.
1.717     albertel 15072: 
                   15073: =item *
                   15074: 
1.243     albertel 15075: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15076: works very similar to store/cstore, but all data is stored in a
                   15077: temporary location and can be reset using tmpreset, $storehash should
                   15078: be a hash reference, returns nothing on success
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15083: similar to restore, but all data is stored in a temporary location and
                   15084: can be reset using tmpreset. Returns a hash of values on success,
                   15085: error string otherwise.
1.191     harris41 15086: 
                   15087: =item *
                   15088: 
1.243     albertel 15089: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15090: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15091: 
                   15092: =item *
                   15093: 
1.243     albertel 15094: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15095: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15096: 
                   15097: =item *
                   15098: 
1.243     albertel 15099: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15100: namesp ($udom and $uname are optional)
1.191     harris41 15101: 
                   15102: =item *
                   15103: 
1.702     albertel 15104: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15105: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15106: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15107: 
1.702     albertel 15108: $range should be either an integer '100' (give me the first 100
                   15109:                                            matching records)
                   15110:               or be  two integers sperated by a - with no spaces
                   15111:                  '30-50' (give me the 30th through the 50th matching
                   15112:                           records)
1.449     matthew  15113: =item *
                   15114: 
                   15115: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15116: $store can be a scalar, an array reference, or if the amount to be 
                   15117: incremented is > 1, a hash reference.
                   15118: 
                   15119: ($udom and $uname are optional)
1.191     harris41 15120: 
                   15121: =item *
                   15122: 
1.243     albertel 15123: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15124: ($udom and $uname are optional)
1.191     harris41 15125: 
                   15126: =item *
                   15127: 
1.243     albertel 15128: cput($namespace,$storehash,$udom,$uname) : critical put
                   15129: ($udom and $uname are optional)
1.191     harris41 15130: 
                   15131: =item *
                   15132: 
1.748     albertel 15133: newput($namespace,$storehash,$udom,$uname) :
                   15134: 
                   15135: Attempts to store the items in the $storehash, but only if they don't
                   15136: currently exist, if this succeeds you can be certain that you have 
                   15137: successfully created a new key value pair in the $namespace db.
                   15138: 
                   15139: 
                   15140: Args:
                   15141:  $namespace: name of database to store values to
                   15142:  $storehash: hashref to store to the db
                   15143:  $udom: (optional) domain of user containing the db
                   15144:  $uname: (optional) name of user caontaining the db
                   15145: 
                   15146: Returns:
                   15147:  'ok' -> succeeded in storing all keys of $storehash
                   15148:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15149:                         least <key> already existed in the db (other
                   15150:                         requested keys may also already exist)
1.967     bisitz   15151:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15152:  'con_lost' -> unable to contact request server
                   15153:  'refused' -> action was not allowed by remote machine
                   15154: 
                   15155: 
                   15156: =item *
                   15157: 
1.243     albertel 15158: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15159: reference filled in from namesp (encrypts the return communication)
                   15160: ($udom and $uname are optional)
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.243     albertel 15164: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15165: critical subroutine
                   15166: 
1.806     raeburn  15167: =item *
                   15168: 
1.860     raeburn  15169: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15170: array reference filled in from namespace found in domain level on either
                   15171: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15172: 
                   15173: =item *
                   15174: 
1.860     raeburn  15175: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15176: domain level either on specified domain server ($uhome) or primary domain 
                   15177: server ($udom and $uhome are optional)
1.806     raeburn  15178: 
1.943     raeburn  15179: =item * 
                   15180: 
1.1172.2.35  raeburn  15181: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15182: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15183: the target domain.
                   15184: 
                   15185: May also include additional key => value pairs for the following groups:
                   15186: 
                   15187: =over
                   15188: 
                   15189: =item
                   15190: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15191: 
                   15192: =over
                   15193: 
                   15194: =item defaultquota, authorquota
                   15195: 
                   15196: =back
                   15197: 
                   15198: =item
                   15199: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15200: portfolio for users).
                   15201: 
                   15202: =over
                   15203: 
                   15204: =item
                   15205: aboutme, blog, webdav, portfolio
                   15206: 
                   15207: =back
                   15208: 
                   15209: =item
                   15210: requestcourses: ability to request courses, and how requests are processed.
                   15211: 
                   15212: =over
                   15213: 
                   15214: =item
1.1172.2.37  raeburn  15215: official, unofficial, community, textbook
1.1172.2.35  raeburn  15216: 
                   15217: =back
                   15218: 
                   15219: =item
                   15220: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15221: 
                   15222: =over
                   15223: 
                   15224: =item
1.1172.2.44  raeburn  15225: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15226: 
                   15227: =back
                   15228: 
                   15229: =item
                   15230: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15231: for course's uploaded content.
                   15232: 
                   15233: =over
                   15234: 
                   15235: =item
1.1172.2.68  raeburn  15236: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15237: communityquota, textbookquota
1.1172.2.35  raeburn  15238: 
                   15239: =back
                   15240: 
                   15241: =item
                   15242: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15243: on your servers.
                   15244: 
                   15245: =over
                   15246: 
                   15247: =item
                   15248: remotesessions, hostedsessions
                   15249: 
                   15250: =back
                   15251: 
                   15252: =back
                   15253: 
                   15254: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15255: utility to create a configuration.db file on a domain's primary library server
                   15256: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15257: -- corresponding values are authentication type (internal, krb4, krb5,
                   15258: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15259: will be available. Values are retrieved from cache (if current), unless the
                   15260: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15261: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15262: 
                   15263: Typical usage:
1.943     raeburn  15264: 
1.1172.2.35  raeburn  15265: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15266: 
1.243     albertel 15267: =back
                   15268: 
                   15269: =head2 Network Status Functions
                   15270: 
                   15271: =over 4
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
1.1137    raeburn  15275: dirlist() : return directory list based on URI (first arg).
                   15276: 
                   15277: Inputs: 1 required, 5 optional.
                   15278: 
                   15279: =over
                   15280: 
                   15281: =item 
                   15282: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15283: 
                   15284: =item
                   15285: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15286: 
                   15287: =item
                   15288: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15289: 
                   15290: =item
                   15291: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15292: 
                   15293: =item
                   15294: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15295: 
                   15296: =item 
                   15297: $alternateRoot - path to prepend in place of path from $uri.
                   15298: 
                   15299: =back
                   15300: 
                   15301: Returns: Array of up to two items.
                   15302: 
                   15303: =over
                   15304: 
                   15305: a reference to an array of files/subdirectories
                   15306: 
                   15307: =over
                   15308: 
                   15309: Each element in the array of files/subdirectories is a & separated list of
                   15310: item name and the result of running stat on the item.  If dirlist was requested
                   15311: for a file instead of a directory, the item name will be ''. For a directory 
                   15312: listing, if the item is a metadata file, the element will end &N&M 
                   15313: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15314: default copyright set (1).  
                   15315: 
                   15316: =back
                   15317: 
                   15318: a scalar containing error condition (if encountered).
                   15319: 
                   15320: =over
                   15321: 
                   15322: =item 
                   15323: no_host (no homeserver identified for $username:$domain).
                   15324: 
                   15325: =item 
                   15326: no_such_host (server contacted for listing not identified as valid host).
                   15327: 
                   15328: =item 
                   15329: con_lost (connection to remote server failed).
                   15330: 
                   15331: =item 
                   15332: refused (invalid $username:$domain received on lond side).
                   15333: 
                   15334: =item 
                   15335: no_such_dir (directory at specified path on lond side does not exist). 
                   15336: 
                   15337: =item 
                   15338: empty (directory at specified path on lond side is empty).
                   15339: 
                   15340: =over
                   15341: 
                   15342: This is currently not encountered because the &ls3, &ls2, 
                   15343: &ls (_handler) routines on the lond side do not filter out
                   15344: . and .. from a directory listing. 
                   15345: 
                   15346: =back
                   15347: 
                   15348: =back
                   15349: 
                   15350: =back
1.191     harris41 15351: 
                   15352: =item *
                   15353: 
1.243     albertel 15354: spareserver() : find server with least workload from spare.tab
                   15355: 
1.986     foxr     15356: 
                   15357: =item *
                   15358: 
                   15359: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15360: if there is no corresponding loncapa host.
                   15361: 
1.243     albertel 15362: =back
                   15363: 
1.986     foxr     15364: 
1.243     albertel 15365: =head2 Apache Request
                   15366: 
                   15367: =over 4
1.191     harris41 15368: 
                   15369: =item *
                   15370: 
1.243     albertel 15371: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15372: localhost, posts hash
                   15373: 
                   15374: =back
                   15375: 
                   15376: =head2 Data to String to Data
                   15377: 
                   15378: =over 4
1.191     harris41 15379: 
                   15380: =item *
                   15381: 
1.243     albertel 15382: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15383: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15384: 
                   15385: =item *
                   15386: 
1.243     albertel 15387: hashref2str($hashref) : convert a hashref into a string complete with
                   15388: escaping and '=' and '&' separators, supports elements that are
                   15389: arrayrefs and hashrefs
1.191     harris41 15390: 
                   15391: =item *
                   15392: 
1.243     albertel 15393: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15394: with escaping and '&' separators, supports elements that are arrayrefs
                   15395: and hashrefs
1.191     harris41 15396: 
                   15397: =item *
                   15398: 
1.243     albertel 15399: str2hash($string) : convert string to hash using unescaping and
                   15400: splitting on '=' and '&', supports elements that are arrayrefs and
                   15401: hashrefs
1.191     harris41 15402: 
                   15403: =item *
                   15404: 
1.243     albertel 15405: str2array($string) : convert string to hash using unescaping and
                   15406: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15407: 
                   15408: =back
                   15409: 
                   15410: =head2 Logging Routines
                   15411: 
                   15412: 
                   15413: These routines allow one to make log messages in the lonnet.log and
                   15414: lonnet.perm logfiles.
1.191     harris41 15415: 
1.1119    foxr     15416: =over 4
                   15417: 
1.191     harris41 15418: =item *
                   15419: 
1.243     albertel 15420: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15421: 
                   15422: =item *
                   15423: 
1.243     albertel 15424: logthis() : append message to the normal lonnet.log file, it gets
                   15425: preiodically rolled over and deleted.
1.191     harris41 15426: 
                   15427: =item *
                   15428: 
1.243     albertel 15429: logperm() : append a permanent message to lonnet.perm.log, this log
                   15430: file never gets deleted by any automated portion of the system, only
                   15431: messages of critical importance should go in here.
                   15432: 
1.1119    foxr     15433: 
1.243     albertel 15434: =back
                   15435: 
                   15436: =head2 General File Helper Routines
                   15437: 
                   15438: =over 4
1.191     harris41 15439: 
                   15440: =item *
                   15441: 
1.481     raeburn  15442: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15443: (a) files in /uploaded
                   15444:   (i) If a local copy of the file exists - 
                   15445:       compares modification date of local copy with last-modified date for 
                   15446:       definitive version stored on home server for course. If local copy is 
                   15447:       stale, requests a new version from the home server and stores it. 
                   15448:       If the original has been removed from the home server, then local copy 
                   15449:       is unlinked.
                   15450:   (ii) If local copy does not exist -
                   15451:       requests the file from the home server and stores it. 
                   15452:   
                   15453:   If $caller is 'uploadrep':  
                   15454:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15455:     for request for files originally uploaded via DOCS. 
                   15456:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15457:   
                   15458:   Otherwise:
                   15459:      This indicates a call from the content generation phase of the request.
                   15460:      -  returns the entire contents of the file or -1.
                   15461:      
                   15462: (b) files in /res
                   15463:    - returns the entire contents of a file or -1; 
                   15464:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15465: 
1.712     albertel 15466: 
                   15467: =item *
                   15468: 
                   15469: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15470:                   reference
                   15471: 
                   15472: returns either a stat() list of data about the file or an empty list
                   15473: if the file doesn't exist or couldn't find out about it (connection
                   15474: problems or user unknown)
                   15475: 
1.191     harris41 15476: =item *
                   15477: 
1.243     albertel 15478: filelocation($dir,$file) : returns file system location of a file
                   15479: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15480: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15481: and a file of ../bob will become /a/bob)
1.191     harris41 15482: 
                   15483: =item *
                   15484: 
                   15485: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15486: filelocation except for hrefs
                   15487: 
                   15488: =item *
                   15489: 
1.1172.2.49  raeburn  15490: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15491: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15492: 
1.243     albertel 15493: =back
                   15494: 
1.608     albertel 15495: =head2 Usererfile file routines (/uploaded*)
                   15496: 
                   15497: =over 4
                   15498: 
                   15499: =item *
                   15500: 
                   15501: userfileupload(): main rotine for putting a file in a user or course's
                   15502:                   filespace, arguments are,
                   15503: 
1.620     albertel 15504:  formname - required - this is the name of the element in $env where the
1.608     albertel 15505:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15506:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15507:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15508:  context - if coursedoc, store the file in the course of the active role
                   15509:              of the current user; 
                   15510:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15511:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15512:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15513:          if undefined, it will be placed in "unknown"
                   15514: 
                   15515:  (This routine calls clean_filename() to remove any dangerous
                   15516:  characters from the filename, and then calls finuserfileupload() to
                   15517:  complete the transaction)
                   15518: 
                   15519:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15520:  and /adm/notfound.html if unsuccessful
                   15521: 
                   15522: =item *
                   15523: 
                   15524: clean_filename(): routine for cleaing a filename up for storage in
                   15525:                  userfile space, argument is:
                   15526: 
                   15527:  filename - proposed filename
                   15528: 
                   15529: returns: the new clean filename
                   15530: 
                   15531: =item *
                   15532: 
1.1090    raeburn  15533: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15534: userspace, probably shouldn't be called directly
                   15535: 
                   15536:   docuname: username or courseid of destination for the file
                   15537:   docudom: domain of user/course of destination for the file
                   15538:   formname: same as for userfileupload()
1.1090    raeburn  15539:   fname: filename (including subdirectories) for the file
                   15540:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15541:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15542:   allfiles: reference to hash used to store objects found by parser
                   15543:   codebase: reference to hash used for codebases of java objects found by parser
                   15544:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15545:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15546:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15547:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15548:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15549:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15550:   mimetype: reference to scalar to accommodate mime type determined
                   15551:             from File::MMagic if $parser = parse.
1.608     albertel 15552: 
                   15553:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15554:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15555:  was 'overwrite').
                   15556:  
1.608     albertel 15557: 
                   15558: =item *
                   15559: 
                   15560: renameuserfile(): renames an existing userfile to a new name
                   15561: 
                   15562:   Args:
                   15563:    docuname: username or courseid of destination for the file
                   15564:    docudom: domain of user/course of destination for the file
                   15565:    old: current file name (including any subdirs under userfiles)
                   15566:    new: desired file name (including any subdirs under userfiles)
                   15567: 
                   15568: =item *
                   15569: 
                   15570: mkdiruserfile(): creates a directory is a userfiles dir
                   15571: 
                   15572:   Args:
                   15573:    docuname: username or courseid of destination for the file
                   15574:    docudom: domain of user/course of destination for the file
                   15575:    dir: dir to create (including any subdirs under userfiles)
                   15576: 
                   15577: =item *
                   15578: 
                   15579: removeuserfile(): removes a file that exists in userfiles
                   15580: 
                   15581:   Args:
                   15582:    docuname: username or courseid of destination for the file
                   15583:    docudom: domain of user/course of destination for the file
                   15584:    fname: filname to delete (including any subdirs under userfiles)
                   15585: 
                   15586: =item *
                   15587: 
                   15588: removeuploadedurl(): convience function for removeuserfile()
                   15589: 
                   15590:   Args:
                   15591:    url:  a full /uploaded/... url to delete
                   15592: 
1.747     albertel 15593: =item * 
                   15594: 
                   15595: get_portfile_permissions():
                   15596:   Args:
                   15597:     domain: domain of user or course contain the portfolio files
                   15598:     user: name of user or num of course contain the portfolio files
                   15599:   Returns:
                   15600:     hashref of a dump of the proper file_permissions.db
                   15601:    
                   15602: 
                   15603: =item * 
                   15604: 
                   15605: get_access_controls():
                   15606: 
                   15607: Args:
                   15608:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15609:   group: (optional) the group you want the files associated with
                   15610:   file: (optional) the file you want access info on
                   15611: 
                   15612: Returns:
1.749     raeburn  15613:     a hash (keys are file names) of hashes containing
                   15614:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15615:         values are XML containing access control settings (see below) 
1.747     albertel 15616: 
                   15617: Internal notes:
                   15618: 
1.749     raeburn  15619:  access controls are stored in file_permissions.db as key=value pairs.
                   15620:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15621:         where scope -> public,guest,course,group,domains or users.
                   15622:               end -> UNIX time for end of access (0 -> no end date)
                   15623:               start -> UNIX time for start of access
                   15624: 
                   15625:     value -> XML description of access control
                   15626:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15627:             <start></start>
                   15628:             <end></end>
                   15629: 
                   15630:             <password></password>  for scope type = guest
                   15631: 
                   15632:             <domain></domain>     for scope type = course or group
                   15633:             <number></number>
                   15634:             <roles id="">
                   15635:              <role></role>
                   15636:              <access></access>
                   15637:              <section></section>
                   15638:              <group></group>
                   15639:             </roles>
                   15640: 
                   15641:             <dom></dom>         for scope type = domains
                   15642: 
                   15643:             <users>             for scope type = users
                   15644:              <user>
                   15645:               <uname></uname>
                   15646:               <udom></udom>
                   15647:              </user>
                   15648:             </users>
                   15649:            </scope> 
                   15650:               
                   15651:  Access data is also aggregated for each file in an additional key=value pair:
                   15652:  key -> path to file/file_name\0accesscontrol 
                   15653:  value -> reference to hash
                   15654:           hash contains key = value pairs
                   15655:           where key = uniqueID:scope_end_start
                   15656:                 value = UNIX time record was last updated
                   15657: 
                   15658:           Used to improve speed of look-ups of access controls for each file.  
                   15659:  
                   15660:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15661: 
1.1172.2.13  raeburn  15662: =item *
                   15663: 
1.749     raeburn  15664: modify_access_controls():
                   15665: 
                   15666: Modifies access controls for a portfolio file
                   15667: Args
                   15668: 1. file name
                   15669: 2. reference to hash of required changes,
                   15670: 3. domain
                   15671: 4. username
                   15672:   where domain,username are the domain of the portfolio owner 
                   15673:   (either a user or a course) 
                   15674: 
                   15675: Returns:
                   15676: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15677: 2. result of deletions ('ok' or 'error', with error message).
                   15678: 3. reference to hash of any new or updated access controls.
                   15679: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15680:    key = integer (inbound ID)
1.1172.2.13  raeburn  15681:    value = uniqueID
                   15682: 
                   15683: =item *
                   15684: 
                   15685: get_timebased_id():
                   15686: 
                   15687: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15688: course via the Course Editor (e.g., folders, composite pages,
                   15689: group bulletin boards).
                   15690: 
                   15691: Args: (first three required; six others optional)
                   15692: 
                   15693: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15694:    docssequence, or name of group
                   15695: 
                   15696: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15697:    e.g., num, boardids
                   15698: 
                   15699: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15700:    file will be named nohist_namespace.db
                   15701: 
                   15702: 4. cdom: domain of course; default is current course domain from %env
                   15703: 
                   15704: 5. cnum: course number; default is current course number from %env
                   15705: 
                   15706: 6. idtype: set to concat if an additional digit is to be appended to the
                   15707:    unix timestamp to form the suffix, if the plain timestamp is already
                   15708:    in use.  Default is to not do this, but simply increment the unix
                   15709:    timestamp by 1 until a unique key is obtained.
                   15710: 
                   15711: 7. who: holder of locking key; defaults to user:domain for user.
                   15712: 
                   15713: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15714:    retrying); default is 3.
                   15715: 
                   15716: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15717: 
                   15718: Returns:
                   15719: 
                   15720: 1. suffix obtained (numeric)
                   15721: 
                   15722: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15723: 
                   15724: 3. error: contains (localized) error message if an error occurred.
                   15725: 
1.747     albertel 15726: 
1.608     albertel 15727: =back
                   15728: 
1.243     albertel 15729: =head2 HTTP Helper Routines
                   15730: 
                   15731: =over 4
                   15732: 
1.191     harris41 15733: =item *
                   15734: 
                   15735: escape() : unpack non-word characters into CGI-compatible hex codes
                   15736: 
                   15737: =item *
                   15738: 
                   15739: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15740: 
1.243     albertel 15741: =back
                   15742: 
                   15743: =head1 PRIVATE SUBROUTINES
                   15744: 
                   15745: =head2 Underlying communication routines (Shouldn't call)
                   15746: 
                   15747: =over 4
                   15748: 
                   15749: =item *
                   15750: 
                   15751: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15752: 
                   15753: =item *
                   15754: 
                   15755: reply() : uses subreply to send a message to remote machine, logs all failures
                   15756: 
                   15757: =item *
                   15758: 
                   15759: critical() : passes a critical message to another server; if cannot
                   15760: get through then place message in connection buffer directory and
                   15761: returns con_delayed, if incapable of saving message, returns
                   15762: con_failed
                   15763: 
                   15764: =item *
                   15765: 
                   15766: reconlonc() : tries to reconnect lonc client processes.
                   15767: 
                   15768: =back
                   15769: 
                   15770: =head2 Resource Access Logging
                   15771: 
                   15772: =over 4
                   15773: 
                   15774: =item *
                   15775: 
                   15776: flushcourselogs() : flush (save) buffer logs and access logs
                   15777: 
                   15778: =item *
                   15779: 
                   15780: courselog($what) : save message for course in hash
                   15781: 
                   15782: =item *
                   15783: 
                   15784: courseacclog($what) : save message for course using &courselog().  Perform
                   15785: special processing for specific resource types (problems, exams, quizzes, etc).
                   15786: 
1.191     harris41 15787: =item *
                   15788: 
                   15789: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15790: as a PerlChildExitHandler
1.243     albertel 15791: 
                   15792: =back
                   15793: 
                   15794: =head2 Other
                   15795: 
                   15796: =over 4
                   15797: 
                   15798: =item *
                   15799: 
                   15800: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15801: 
                   15802: =back
                   15803: 
                   15804: =cut
1.877     foxr     15805: 

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