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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .4(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.118.2.3 2020/01/21 15:36:29 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  266:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  269:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  960:20):                 my $protocol = 'http';
                    961:20):                 if ($protocol{$spare_server} eq 'https') {
                    962:20):                     $protocol = $protocol{$spare_server};
                    963:20):                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
                   1085: sub delbalcookie {
                   1086:     my ($cookie,$balancer) =@_;
                   1087:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:         my ($udom,$uname) = ($1,$2);
                   1089:         my $uprimary_id = &domain($udom,'primary');
                   1090:         my $uintdom = &internet_dom($uprimary_id);
                   1091:         my $intdom = &internet_dom($balancer);
                   1092:         my $serverhomedom = &host_domain($balancer);
                   1093:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:             return &reply("delbalcookie:$cookie",$balancer);
                   1095:         }
                   1096:     }
                   1097: }
                   1098: 
1.914     albertel 1099: # -------------------------------- ask if server already has a session for user
                   1100: sub has_user_session {
                   1101:     my ($lonid,$udom,$uname) = @_;
                   1102:     my $result = &reply(join(':','userhassession',
                   1103: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1104:     return 1 if ($result eq 'ok');
                   1105: 
                   1106:     return 0;
                   1107: }
                   1108: 
1.1076    raeburn  1109: # --------- determine least loaded server in a user's domain which allows login
                   1110: 
                   1111: sub choose_server {
1.1172.2.47  raeburn  1112:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1113:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1114:     my %servers = &get_servers($udom);
1.1076    raeburn  1115:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1116:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1117:     if ($skiploadbal) {
                   1118:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1119:         unless (defined($cached)) {
                   1120:             my $cachetime = 60*60*24;
                   1121:             my %domconfig =
                   1122:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1123:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1124:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1125:                                            $cachetime);
                   1126:             }
                   1127:         }
                   1128:     }
1.1076    raeburn  1129:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1130:         my $loginvia;
1.1172.2.47  raeburn  1131:         if ($skiploadbal) {
                   1132:             if (ref($balancers) eq 'HASH') {
                   1133:                 next if (exists($balancers->{$lonhost}));
                   1134:             }
                   1135:         }
1.1115    raeburn  1136:         if ($checkloginvia) {
                   1137:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1138:             if ($loginvia) {
                   1139:                 my ($server,$path) = split(/:/,$loginvia);
                   1140:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1141:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1142:                 if ($login_host eq $server) {
                   1143:                     $portal_path = $path;
1.1151    raeburn  1144:                     $isredirect = 1;
1.1116    raeburn  1145:                 }
                   1146:             } else {
                   1147:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1148:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1149:                 if ($login_host eq $lonhost) {
                   1150:                     $portal_path = '';
1.1151    raeburn  1151:                     $isredirect = ''; 
1.1116    raeburn  1152:                 }
                   1153:             }
                   1154:         } else {
1.1076    raeburn  1155:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1157:         }
                   1158:     }
                   1159:     if ($login_host ne '') {
1.1116    raeburn  1160:         $hostname = &hostname($login_host);
1.1076    raeburn  1161:     }
1.1172.2.88  raeburn  1162:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1163: }
                   1164: 
1.202     matthew  1165: # --------------------------------------------- Try to change a user's password
                   1166: 
                   1167: sub changepass {
1.799     raeburn  1168:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1169:     $currentpass = &escape($currentpass);
                   1170:     $newpass     = &escape($newpass);
1.1030    raeburn  1171:     my $lonhost = $perlvar{'lonHostID'};
                   1172:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1173: 		       $server);
                   1174:     if (! $answer) {
                   1175: 	&logthis("No reply on password change request to $server ".
                   1176: 		 "by $uname in domain $udom.");
                   1177:     } elsif ($answer =~ "^ok") {
                   1178:         &logthis("$uname in $udom successfully changed their password ".
                   1179: 		 "on $server.");
                   1180:     } elsif ($answer =~ "^pwchange_failure") {
                   1181: 	&logthis("$uname in $udom was unable to change their password ".
                   1182: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1183: 		 "or pwchange");
                   1184:     } elsif ($answer =~ "^non_authorized") {
                   1185:         &logthis("$uname in $udom did not get their password correct when ".
                   1186: 		 "attempting to change it on $server.");
                   1187:     } elsif ($answer =~ "^auth_mode_error") {
                   1188:         &logthis("$uname in $udom attempted to change their password despite ".
                   1189: 		 "not being locally or internally authenticated on $server.");
                   1190:     } elsif ($answer =~ "^unknown_user") {
                   1191:         &logthis("$uname in $udom attempted to change their password ".
                   1192: 		 "on $server but were unable to because $server is not ".
                   1193: 		 "their home server.");
                   1194:     } elsif ($answer =~ "^refused") {
                   1195: 	&logthis("$server refused to change $uname in $udom password because ".
                   1196: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1197:     } elsif ($answer =~ "invalid_client") {
                   1198:         &logthis("$server refused to change $uname in $udom password because ".
                   1199:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1200:     } elsif ($answer =~ "^prioruse") {
                   1201:        &logthis("$server refused to change $uname in $udom password because ".
                   1202:                 "the password had been used before");
1.202     matthew  1203:     }
                   1204:     return $answer;
1.1       albertel 1205: }
                   1206: 
1.169     harris41 1207: # ----------------------- Try to determine user's current authentication scheme
                   1208: 
                   1209: sub queryauthenticate {
                   1210:     my ($uname,$udom)=@_;
1.456     albertel 1211:     my $uhome=&homeserver($uname,$udom);
                   1212:     if (!$uhome) {
                   1213: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1214: 	return 'no_host';
                   1215:     }
                   1216:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1217:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1218: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1219:     }
1.456     albertel 1220:     return $answer;
1.169     harris41 1221: }
                   1222: 
1.1       albertel 1223: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1224: 
1.1       albertel 1225: sub authenticate {
1.1073    raeburn  1226:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1227:     $upass=&escape($upass);
                   1228:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1229:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1230:     my $newhome;
1.836     www      1231:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1232: # Maybe the machine was offline and only re-appeared again recently?
                   1233:         &reconlonc();
                   1234: # One more
1.952     raeburn  1235: 	$uhome=&homeserver($uname,$udom,1);
                   1236:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1237:             if (defined(&domain($udom,'primary'))) {
                   1238:                 $newhome=&domain($udom,'primary');
                   1239:             }
                   1240:             if ($newhome ne '') {
                   1241:                 $uhome = $newhome;
                   1242:             }
                   1243:         }
1.836     www      1244: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1245: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1246: 	    return 'no_host';
                   1247:         }
1.1       albertel 1248:     }
1.1073    raeburn  1249:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1250:     if ($answer eq 'authorized') {
1.952     raeburn  1251:         if ($newhome) {
                   1252:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1253:             return 'no_account_on_host'; 
                   1254:         } else {
                   1255:             &logthis("User $uname at $udom authorized by $uhome");
                   1256:             return $uhome;
                   1257:         }
1.471     albertel 1258:     }
                   1259:     if ($answer eq 'non_authorized') {
                   1260: 	&logthis("User $uname at $udom rejected by $uhome");
                   1261: 	return 'no_host'; 
1.9       www      1262:     }
1.471     albertel 1263:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1264:     return 'no_host';
                   1265: }
                   1266: 
1.1073    raeburn  1267: sub can_host_session {
1.1074    raeburn  1268:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1269:     my $canhost = 1;
1.1074    raeburn  1270:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1271:     if (ref($remotesessions) eq 'HASH') {
                   1272:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1273:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1274:                 $canhost = 0;
                   1275:             } else {
                   1276:                 $canhost = 1;
                   1277:             }
                   1278:         }
                   1279:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1280:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1281:                 $canhost = 1;
                   1282:             } else {
                   1283:                 $canhost = 0;
                   1284:             }
                   1285:         }
                   1286:         if ($canhost) {
                   1287:             if ($remotesessions->{'version'} ne '') {
                   1288:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1289:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1290:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1291:                         my $major = $1;
                   1292:                         my $minor = $2;
                   1293:                         if (($major < $reqmajor ) ||
                   1294:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1295:                             $canhost = 0;
                   1296:                         }
                   1297:                     } else {
                   1298:                         $canhost = 0;
                   1299:                     }
                   1300:                 }
                   1301:             }
                   1302:         }
                   1303:     }
                   1304:     if ($canhost) {
                   1305:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1306:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1307:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1308:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1309:                 if (($uint_dom ne '') && 
                   1310:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1311:                     $canhost = 0;
                   1312:                 } else {
                   1313:                     $canhost = 1;
                   1314:                 }
                   1315:             }
                   1316:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1317:                 if (($uint_dom ne '') && 
                   1318:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1319:                     $canhost = 1;
                   1320:                 } else {
                   1321:                     $canhost = 0;
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     return $canhost;
                   1327: }
                   1328: 
1.1083    raeburn  1329: sub spare_can_host {
                   1330:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1331:     my $canhost=1;
1.1172.2.62  raeburn  1332:     my $try_server_hostname = &hostname($try_server);
                   1333:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1334:     my $serverhomedom = &host_domain($serverhomeID);
                   1335:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1336:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1337:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1338:             $canhost = 0;
                   1339:         }
                   1340:     }
                   1341:     if (($canhost) && ($uint_dom)) {
                   1342:         my @intdoms;
                   1343:         my $internet_names = &get_internet_names($try_server);
                   1344:         if (ref($internet_names) eq 'ARRAY') {
                   1345:             @intdoms = @{$internet_names};
                   1346:         }
                   1347:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1348:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1349:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1350:                                          $remotesessions,
                   1351:                                          $defdomdefaults{'hostedsessions'});
                   1352:         }
1.1083    raeburn  1353:     }
                   1354:     return $canhost;
                   1355: }
                   1356: 
1.1123    raeburn  1357: sub this_host_spares {
                   1358:     my ($dom) = @_;
1.1126    raeburn  1359:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1360:     my @hosts = &current_machine_ids();
                   1361:     foreach my $lonhost (@hosts) {
                   1362:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1363:             $dom_in_use = $dom;
                   1364:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1365:             last;
                   1366:         }
                   1367:     }
1.1126    raeburn  1368:     if ($dom_in_use ne '') {
                   1369:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1370:     }
                   1371:     if (ref($result) ne 'HASH') {
                   1372:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1373:         $dom_in_use = &host_domain($lonhost_in_use);
                   1374:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1375:         if (ref($result) ne 'HASH') {
                   1376:             $result = \%spareid;
                   1377:         }
                   1378:     }
                   1379:     return $result;
                   1380: }
                   1381: 
                   1382: sub spares_for_offload  {
                   1383:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1384:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1385:     if (defined($cached)) {
                   1386:         return $result;
                   1387:     } else {
1.1126    raeburn  1388:         my $cachetime = 60*60*24;
                   1389:         my %domconfig =
                   1390:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1391:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1392:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1393:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1394:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1395:                 }
                   1396:             }
                   1397:         }
                   1398:     }
1.1126    raeburn  1399:     return;
1.1123    raeburn  1400: }
                   1401: 
1.1129    raeburn  1402: sub get_lonbalancer_config {
                   1403:     my ($servers) = @_;
                   1404:     my ($currbalancer,$currtargets);
                   1405:     if (ref($servers) eq 'HASH') {
                   1406:         foreach my $server (keys(%{$servers})) {
                   1407:             my %what = (
                   1408:                          spareid => 1,
                   1409:                          perlvar => 1,
                   1410:                        );
                   1411:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1412:             if ($result eq 'ok') {
                   1413:                 if (ref($returnhash) eq 'HASH') {
                   1414:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1415:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1416:                             $currbalancer = $server;
                   1417:                             $currtargets = {};
                   1418:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1419:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1420:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1421:                                 }
                   1422:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1423:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1424:                                 }
                   1425:                             }
                   1426:                             last;
                   1427:                         }
                   1428:                     }
                   1429:                 }
                   1430:             }
                   1431:         }
                   1432:     }
                   1433:     return ($currbalancer,$currtargets);
                   1434: }
                   1435: 
                   1436: sub check_loadbalancing {
1.1172.2.88  raeburn  1437:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1438:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1439:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1440:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1441:     my @hosts = &current_machine_ids();
1.1129    raeburn  1442:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1443:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1444:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1445:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1446:     my $domneedscache; 
1.1129    raeburn  1447:     my $cachetime = 60*60*24;
                   1448: 
                   1449:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1450:         $dom_in_use = $udom;
                   1451:         $homeintdom = 1;
                   1452:     } else {
                   1453:         $dom_in_use = $serverhomedom;
                   1454:     }
                   1455:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1456:     unless (defined($cached)) {
                   1457:         my %domconfig =
                   1458:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1459:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1460:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1461:         } else {
                   1462:             $domneedscache = $dom_in_use;
1.1129    raeburn  1463:         }
                   1464:     }
                   1465:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1466:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1467:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1468:         if ($is_balancer) {
                   1469:             if (ref($currrules) eq 'HASH') {
                   1470:                 if ($homeintdom) {
                   1471:                     if ($uname ne '') {
                   1472:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1473:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1474:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1475:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1476:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1477:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1478:                             }
                   1479:                         }
                   1480:                         if ($rule_in_effect eq '') {
                   1481:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1482:                             if ($userenv{'inststatus'} ne '') {
                   1483:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1484:                                 my ($othertitle,$usertypes,$types) =
                   1485:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1486:                                 if (ref($types) eq 'ARRAY') {
                   1487:                                     foreach my $type (@{$types}) {
                   1488:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1489:                                             if (exists($currrules->{$type})) {
                   1490:                                                 $rule_in_effect = $currrules->{$type};
                   1491:                                             }
                   1492:                                         }
                   1493:                                     }
                   1494:                                 }
                   1495:                             } else {
                   1496:                                 if (exists($currrules->{'default'})) {
                   1497:                                     $rule_in_effect = $currrules->{'default'};
                   1498:                                 }
                   1499:                             }
                   1500:                         }
                   1501:                     } else {
                   1502:                         if (exists($currrules->{'default'})) {
                   1503:                             $rule_in_effect = $currrules->{'default'};
                   1504:                         }
                   1505:                     }
                   1506:                 } else {
                   1507:                     if ($currrules->{'_LC_external'} ne '') {
                   1508:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1509:                     }
                   1510:                 }
                   1511:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1512:                                                        $uname,$udom);
                   1513:             }
                   1514:         }
                   1515:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1516:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1517:         unless (defined($cached)) {
                   1518:             my %domconfig =
                   1519:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1520:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1521:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1522:             } else {
                   1523:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1524:             }
                   1525:         }
                   1526:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1527:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1528:                 &check_balancer_result($result,@hosts);
                   1529:             if ($is_balancer) {
1.1129    raeburn  1530:                 if (ref($currrules) eq 'HASH') {
                   1531:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1532:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1533:                     }
                   1534:                 }
                   1535:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1536:                                                        $uname,$udom);
                   1537:             }
                   1538:         } else {
                   1539:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1540:                 $is_balancer = 1;
                   1541:                 $offloadto = &this_host_spares($dom_in_use);
                   1542:             }
1.1172.2.75  raeburn  1543:             unless (defined($cached)) {
                   1544:                 $domneedscache = $serverhomedom;
                   1545:             }
1.1129    raeburn  1546:         }
                   1547:     } else {
                   1548:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1549:             $is_balancer = 1;
                   1550:             $offloadto = &this_host_spares($dom_in_use);
                   1551:         }
1.1172.2.75  raeburn  1552:         unless (defined($cached)) {
                   1553:             $domneedscache = $serverhomedom;
                   1554:         }
                   1555:     }
                   1556:     if ($domneedscache) {
                   1557:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1558:     }
1.1172.2.5  raeburn  1559:     if ($is_balancer) {
                   1560:         my $lowest_load = 30000;
                   1561:         if (ref($offloadto) eq 'HASH') {
                   1562:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1563:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1564:                     ($otherserver,$lowest_load) =
                   1565:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1566:                 }
1.1129    raeburn  1567:             }
1.1172.2.5  raeburn  1568:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1569: 
1.1172.2.5  raeburn  1570:             if (!$found_server) {
                   1571:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1572:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1573:                         ($otherserver,$lowest_load) =
                   1574:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1575:                     }
                   1576:                 }
                   1577:             }
                   1578:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1579:             if (@{$offloadto} == 1) {
                   1580:                 $otherserver = $offloadto->[0];
                   1581:             } elsif (@{$offloadto} > 1) {
                   1582:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1583:                     ($otherserver,$lowest_load) =
                   1584:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1585:                 }
                   1586:             }
                   1587:         }
1.1172.2.88  raeburn  1588:         unless ($caller eq 'login') {
                   1589:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1590:                 $is_balancer = 0;
                   1591:                 if ($uname ne '' && $udom ne '') {
                   1592:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1593:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1594:                                  'user.loadbalcheck.time' => time});
                   1595:                     }
1.1172.2.5  raeburn  1596:                 }
1.1129    raeburn  1597:             }
                   1598:         }
1.1172.2.107  raeburn  1599:         unless ($homeintdom) {
                   1600:             undef($setcookie);
                   1601:         }
1.1129    raeburn  1602:     }
1.1172.2.107  raeburn  1603:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1604: }
                   1605: 
1.1172.2.12  raeburn  1606: sub check_balancer_result {
                   1607:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1608:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1609:     if (ref($result) eq 'HASH') {
                   1610:         if ($result->{'lonhost'} ne '') {
                   1611:             my $currbalancer = $result->{'lonhost'};
                   1612:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1613:                 $is_balancer = 1;
                   1614:                 $currtargets = $result->{'targets'};
                   1615:                 $currrules = $result->{'rules'};
                   1616:             }
                   1617:         } else {
                   1618:             foreach my $key (keys(%{$result})) {
                   1619:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1620:                     (ref($result->{$key}) eq 'HASH')) {
                   1621:                     $is_balancer = 1;
                   1622:                     $currrules = $result->{$key}{'rules'};
                   1623:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1624:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1625:                     last;
                   1626:                 }
                   1627:             }
                   1628:         }
                   1629:     }
1.1172.2.107  raeburn  1630:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1631: }
                   1632: 
1.1129    raeburn  1633: sub get_loadbalancer_targets {
                   1634:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1635:     my $offloadto;
1.1172.2.4  raeburn  1636:     if ($rule_in_effect eq 'none') {
                   1637:         return [$perlvar{'lonHostID'}];
                   1638:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1639:         $offloadto = $currtargets;
                   1640:     } else {
                   1641:         if ($rule_in_effect eq 'homeserver') {
                   1642:             my $homeserver = &homeserver($uname,$udom);
                   1643:             if ($homeserver ne 'no_host') {
                   1644:                 $offloadto = [$homeserver];
                   1645:             }
                   1646:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1647:             my %domconfig =
                   1648:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1649:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1650:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1651:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1652:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1653:                     }
                   1654:                 }
                   1655:             } else {
1.1172.2.7  raeburn  1656:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1657:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1658:                 if (&hostname($remotebalancer) ne '') {
                   1659:                     $offloadto = [$remotebalancer];
                   1660:                 }
                   1661:             }
                   1662:         } elsif (&hostname($rule_in_effect) ne '') {
                   1663:             $offloadto = [$rule_in_effect];
                   1664:         }
                   1665:     }
                   1666:     return $offloadto;
                   1667: }
                   1668: 
1.1127    raeburn  1669: sub internet_dom_servers {
                   1670:     my ($dom) = @_;
                   1671:     my (%uniqservers,%servers);
                   1672:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1673:     my @machinedoms = &machine_domains($primaryserver);
                   1674:     foreach my $mdom (@machinedoms) {
                   1675:         my %currservers = %servers;
                   1676:         my %server = &get_servers($mdom);
                   1677:         %servers = (%currservers,%server);
                   1678:     }
                   1679:     my %by_hostname;
                   1680:     foreach my $id (keys(%servers)) {
                   1681:         push(@{$by_hostname{$servers{$id}}},$id);
                   1682:     }
                   1683:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1684:         if (@{$by_hostname{$hostname}} > 1) {
                   1685:             my $match = 0;
                   1686:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1687:                 if (&host_domain($id) eq $dom) {
                   1688:                     $uniqservers{$id} = $hostname;
                   1689:                     $match = 1;
                   1690:                 }
                   1691:             }
                   1692:             unless ($match) {
                   1693:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1694:             }
                   1695:         } else {
                   1696:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1697:         }
                   1698:     }
                   1699:     return %uniqservers;
                   1700: }
                   1701: 
1.1       albertel 1702: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1703: 
1.599     albertel 1704: my %homecache;
1.1       albertel 1705: sub homeserver {
1.230     stredwic 1706:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1707:     my $index="$uname:$udom";
1.426     albertel 1708: 
1.599     albertel 1709:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1710: 
                   1711:     my %servers = &get_servers($udom,'library');
                   1712:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1713:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1714: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1715: 
                   1716: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1717: 	if ($answer eq 'found') {
                   1718: 	    delete($badServerCache{$tryserver}); 
                   1719: 	    return $homecache{$index}=$tryserver;
                   1720: 	} elsif ($answer eq 'no_host') {
                   1721: 	    $badServerCache{$tryserver}=1;
                   1722: 	}
1.1       albertel 1723:     }    
                   1724:     return 'no_host';
1.70      www      1725: }
                   1726: 
                   1727: # ------------------------------------- Find the usernames behind a list of IDs
                   1728: 
                   1729: sub idget {
                   1730:     my ($udom,@ids)=@_;
                   1731:     my %returnhash=();
                   1732:     
1.841     albertel 1733:     my %servers = &get_servers($udom,'library');
                   1734:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1735: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1736: 	$idlist=~tr/A-Z/a-z/; 
                   1737: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1738: 	my @answer=();
                   1739: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1740: 	    @answer=split(/\&/,$reply);
                   1741: 	}                    ;
                   1742: 	my $i;
                   1743: 	for ($i=0;$i<=$#ids;$i++) {
                   1744: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1745: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1746: 	    } 
                   1747: 	}
                   1748:     } 
1.70      www      1749:     return %returnhash;
                   1750: }
                   1751: 
                   1752: # ------------------------------------- Find the IDs behind a list of usernames
                   1753: 
                   1754: sub idrget {
                   1755:     my ($udom,@unames)=@_;
                   1756:     my %returnhash=();
1.800     albertel 1757:     foreach my $uname (@unames) {
                   1758:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1759:     }
1.70      www      1760:     return %returnhash;
                   1761: }
                   1762: 
                   1763: # ------------------------------- Store away a list of names and associated IDs
                   1764: 
                   1765: sub idput {
                   1766:     my ($udom,%ids)=@_;
                   1767:     my %servers=();
1.800     albertel 1768:     foreach my $uname (keys(%ids)) {
                   1769: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1770:         my $uhom=&homeserver($uname,$udom);
1.70      www      1771:         if ($uhom ne 'no_host') {
1.800     albertel 1772:             my $id=&escape($ids{$uname});
1.70      www      1773:             $id=~tr/A-Z/a-z/;
1.800     albertel 1774:             my $esc_unam=&escape($uname);
1.70      www      1775: 	    if ($servers{$uhom}) {
1.800     albertel 1776: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1777:             } else {
1.800     albertel 1778:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1779:             }
                   1780:         }
1.191     harris41 1781:     }
1.800     albertel 1782:     foreach my $server (keys(%servers)) {
                   1783:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1784:     }
1.344     www      1785: }
                   1786: 
1.1172.2.30  raeburn  1787: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1788: 
                   1789: sub iddel {
                   1790:     my ($udom,$idshashref,$uhome)=@_;
                   1791:     my %result=();
                   1792:     unless (ref($idshashref) eq 'HASH') {
                   1793:         return %result;
                   1794:     }
                   1795:     my %servers=();
                   1796:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1797:         my $uhom;
                   1798:         if ($uhome) {
                   1799:             $uhom = $uhome;
                   1800:         } else {
                   1801:             $uhom=&homeserver($uname,$udom);
                   1802:         }
                   1803:         if ($uhom ne 'no_host') {
                   1804:             if ($servers{$uhom}) {
                   1805:                 $servers{$uhom}.='&'.&escape($id);
                   1806:             } else {
                   1807:                 $servers{$uhom}=&escape($id);
                   1808:             }
                   1809:         }
                   1810:     }
                   1811:     foreach my $server (keys(%servers)) {
                   1812:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1813:     }
                   1814:     return %result;
                   1815: }
                   1816: 
1.1023    raeburn  1817: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1818: sub dump_dom {
1.1165    droeschl 1819:     my ($namespace, $udom, $regexp) = @_;
                   1820: 
                   1821:     $udom ||= $env{'user.domain'};
                   1822: 
                   1823:     return () unless $udom;
                   1824: 
                   1825:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1826: }
                   1827: 
1.1023    raeburn  1828: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1829: 
                   1830: sub get_dom {
1.860     raeburn  1831:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1832:     return if ($udom eq 'public');
1.806     raeburn  1833:     my $items='';
                   1834:     foreach my $item (@$storearr) {
                   1835:         $items.=&escape($item).'&';
                   1836:     }
                   1837:     $items=~s/\&$//;
1.860     raeburn  1838:     if (!$udom) {
                   1839:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1840:         return if ($udom eq 'public');
1.860     raeburn  1841:         if (defined(&domain($udom,'primary'))) {
                   1842:             $uhome=&domain($udom,'primary');
                   1843:         } else {
1.874     albertel 1844:             undef($uhome);
1.860     raeburn  1845:         }
                   1846:     } else {
                   1847:         if (!$uhome) {
                   1848:             if (defined(&domain($udom,'primary'))) {
                   1849:                 $uhome=&domain($udom,'primary');
                   1850:             }
                   1851:         }
                   1852:     }
                   1853:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1854:20):         my $rep;
                   1855:20):         if ($namespace =~ /^enc/) {
                   1856:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1857:20):         } else {
                   1858:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1859:20):         }
1.866     raeburn  1860:         my %returnhash;
1.875     albertel 1861:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1862:             return %returnhash;
                   1863:         }
1.806     raeburn  1864:         my @pairs=split(/\&/,$rep);
                   1865:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1866:             return @pairs;
                   1867:         }
                   1868:         my $i=0;
                   1869:         foreach my $item (@$storearr) {
                   1870:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1871:             $i++;
                   1872:         }
                   1873:         return %returnhash;
                   1874:     } else {
1.880     banghart 1875:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1876:     }
                   1877: }
                   1878: 
                   1879: # -------------------------------------------- put items in domain db files 
                   1880: 
                   1881: sub put_dom {
1.860     raeburn  1882:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1883:     if (!$udom) {
                   1884:         $udom=$env{'user.domain'};
                   1885:         if (defined(&domain($udom,'primary'))) {
                   1886:             $uhome=&domain($udom,'primary');
                   1887:         } else {
1.874     albertel 1888:             undef($uhome);
1.860     raeburn  1889:         }
                   1890:     } else {
                   1891:         if (!$uhome) {
                   1892:             if (defined(&domain($udom,'primary'))) {
                   1893:                 $uhome=&domain($udom,'primary');
                   1894:             }
                   1895:         }
                   1896:     } 
                   1897:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1898:         my $items='';
                   1899:         foreach my $item (keys(%$storehash)) {
                   1900:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1901:         }
                   1902:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1903:20):         if ($namespace =~ /^enc/) {
                   1904:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1905:20):         } else {
                   1906:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1907:20):         }
1.806     raeburn  1908:     } else {
1.860     raeburn  1909:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1910:     }
                   1911: }
                   1912: 
1.1023    raeburn  1913: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1914: sub newput_dom {
1.1023    raeburn  1915:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1916:     my $result;
                   1917:     if (!$udom) {
                   1918:         $udom=$env{'user.domain'};
                   1919:     }
1.1023    raeburn  1920:     if ($udom) {
                   1921:         my $uname = &get_domainconfiguser($udom);
                   1922:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1923:     }
                   1924:     return $result;
                   1925: }
                   1926: 
1.1023    raeburn  1927: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1928: sub del_dom {
1.1023    raeburn  1929:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1930:     if (ref($storearr) eq 'ARRAY') {
                   1931:         if (!$udom) {
                   1932:             $udom=$env{'user.domain'};
                   1933:         }
1.1023    raeburn  1934:         if ($udom) {
                   1935:             my $uname = &get_domainconfiguser($udom); 
                   1936:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1937:         }
                   1938:     }
                   1939: }
                   1940: 
1.1023    raeburn  1941: # ----------------------------------construct domainconfig user for a domain 
                   1942: sub get_domainconfiguser {
                   1943:     my ($udom) = @_;
                   1944:     return $udom.'-domainconfig';
                   1945: }
                   1946: 
1.837     raeburn  1947: sub retrieve_inst_usertypes {
                   1948:     my ($udom) = @_;
                   1949:     my (%returnhash,@order);
1.989     raeburn  1950:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1951:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1952:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1953:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1954:     } else {
                   1955:         if (defined(&domain($udom,'primary'))) {
                   1956:             my $uhome=&domain($udom,'primary');
                   1957:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1958:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1959:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1960:                 return (\%returnhash,\@order);
                   1961:             }
                   1962:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1963:             my @pairs=split(/\&/,$hashitems);
                   1964:             foreach my $item (@pairs) {
                   1965:                 my ($key,$value)=split(/=/,$item,2);
                   1966:                 $key = &unescape($key);
                   1967:                 next if ($key =~ /^error: 2 /);
                   1968:                 $returnhash{$key}=&thaw_unescape($value);
                   1969:             }
                   1970:             my @esc_order = split(/\&/,$orderitems);
                   1971:             foreach my $item (@esc_order) {
                   1972:                 push(@order,&unescape($item));
                   1973:             }
                   1974:         } else {
1.1172.2.44  raeburn  1975:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1976:         }
1.1172.2.44  raeburn  1977:         return (\%returnhash,\@order);
1.837     raeburn  1978:     }
                   1979: }
                   1980: 
1.868     raeburn  1981: sub is_domainimage {
                   1982:     my ($url) = @_;
1.1172.2.74  raeburn  1983:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1984:         if (&domain($1) ne '') {
                   1985:             return '1';
                   1986:         }
                   1987:     }
                   1988:     return;
                   1989: }
                   1990: 
1.899     raeburn  1991: sub inst_directory_query {
                   1992:     my ($srch) = @_;
                   1993:     my $udom = $srch->{'srchdomain'};
                   1994:     my %results;
                   1995:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1996:     my $outcome;
1.899     raeburn  1997:     if ($homeserver ne '') {
1.1172.2.116  raeburn  1998:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   1999:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2000:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2001:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2002:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2003:                     (($major == 2) && ($minor < 11)) ||
                   2004:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2005:                     return;
                   2006:                 }
                   2007:             }
                   2008:         }
1.904     albertel 2009: 	my $queryid=&reply("querysend:instdirsearch:".
                   2010: 			   &escape($srch->{'srchby'}).':'.
                   2011: 			   &escape($srch->{'srchterm'}).':'.
                   2012: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2013: 	my $host=&hostname($homeserver);
                   2014: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2015: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2016: 	    return;
                   2017: 	}
                   2018: 	my $response = &get_query_reply($queryid);
                   2019: 	my $maxtries = 5;
                   2020: 	my $tries = 1;
                   2021: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2022: 	    $response = &get_query_reply($queryid);
                   2023: 	    $tries ++;
                   2024: 	}
                   2025: 
                   2026:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2027:             if ($response eq 'unavailable') {
                   2028:                 $outcome = $response;
                   2029:             } else {
                   2030:                 $outcome = 'ok';
                   2031:                 my @matches = split(/\n/,$response);
                   2032:                 foreach my $match (@matches) {
                   2033:                     my ($key,$value) = split(/=/,$match);
                   2034:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2035:                 }
1.899     raeburn  2036:             }
                   2037:         }
                   2038:     }
1.909     raeburn  2039:     return ($outcome,%results);
1.899     raeburn  2040: }
                   2041: 
                   2042: sub usersearch {
                   2043:     my ($srch) = @_;
                   2044:     my $dom = $srch->{'srchdomain'};
                   2045:     my %results;
                   2046:     my %libserv = &all_library();
                   2047:     my $query = 'usersearch';
                   2048:     foreach my $tryserver (keys(%libserv)) {
                   2049:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2050:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2051:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2052:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2053:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2054:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2055:                              (($major == 2) && ($minor < 11)) ||
                   2056:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2057:                 }
                   2058:             }
1.899     raeburn  2059:             my $host=&hostname($tryserver);
                   2060:             my $queryid=
1.911     raeburn  2061:                 &reply("querysend:".&escape($query).':'.
                   2062:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2063:                        &escape($srch->{'srchtype'}).':'.
                   2064:                        &escape($srch->{'srchterm'}),$tryserver);
                   2065:             if ($queryid !~/^\Q$host\E\_/) {
                   2066:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2067:                 next;
1.899     raeburn  2068:             }
                   2069:             my $reply = &get_query_reply($queryid);
                   2070:             my $maxtries = 1;
                   2071:             my $tries = 1;
                   2072:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2073:                 $reply = &get_query_reply($queryid);
                   2074:                 $tries ++;
                   2075:             }
                   2076:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2077:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2078:             } else {
1.911     raeburn  2079:                 my @matches;
                   2080:                 if ($reply =~ /\n/) {
                   2081:                     @matches = split(/\n/,$reply);
                   2082:                 } else {
                   2083:                     @matches = split(/\&/,$reply);
                   2084:                 }
1.899     raeburn  2085:                 foreach my $match (@matches) {
                   2086:                     my ($uname,$udom,%userhash);
1.911     raeburn  2087:                     foreach my $entry (split(/:/,$match)) {
                   2088:                         my ($key,$value) =
                   2089:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2090:                         $userhash{$key} = $value;
                   2091:                         if ($key eq 'username') {
                   2092:                             $uname = $value;
                   2093:                         } elsif ($key eq 'domain') {
                   2094:                             $udom = $value;
1.911     raeburn  2095:                         }
1.899     raeburn  2096:                     }
                   2097:                     $results{$uname.':'.$udom} = \%userhash;
                   2098:                 }
                   2099:             }
                   2100:         }
                   2101:     }
                   2102:     return %results;
                   2103: }
                   2104: 
1.912     raeburn  2105: sub get_instuser {
                   2106:     my ($udom,$uname,$id) = @_;
                   2107:     my $homeserver = &domain($udom,'primary');
                   2108:     my ($outcome,%results);
                   2109:     if ($homeserver ne '') {
                   2110:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2111:                            &escape($id).':'.&escape($udom),$homeserver);
                   2112:         my $host=&hostname($homeserver);
                   2113:         if ($queryid !~/^\Q$host\E\_/) {
                   2114:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2115:             return;
                   2116:         }
                   2117:         my $response = &get_query_reply($queryid);
                   2118:         my $maxtries = 5;
                   2119:         my $tries = 1;
                   2120:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2121:             $response = &get_query_reply($queryid);
                   2122:             $tries ++;
                   2123:         }
                   2124:         if (!&error($response) && $response ne 'refused') {
                   2125:             if ($response eq 'unavailable') {
                   2126:                 $outcome = $response;
                   2127:             } else {
                   2128:                 $outcome = 'ok';
                   2129:                 my @matches = split(/\n/,$response);
                   2130:                 foreach my $match (@matches) {
                   2131:                     my ($key,$value) = split(/=/,$match);
                   2132:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2133:                 }
                   2134:             }
                   2135:         }
                   2136:     }
                   2137:     my %userinfo;
                   2138:     if (ref($results{$uname}) eq 'HASH') {
                   2139:         %userinfo = %{$results{$uname}};
                   2140:     } 
                   2141:     return ($outcome,%userinfo);
                   2142: }
                   2143: 
1.1172.2.69  raeburn  2144: sub get_multiple_instusers {
                   2145:     my ($udom,$users,$caller) = @_;
                   2146:     my ($outcome,$results);
                   2147:     if (ref($users) eq 'HASH') {
                   2148:         my $count = keys(%{$users});
                   2149:         my $requested = &freeze_escape($users);
                   2150:         my $homeserver = &domain($udom,'primary');
                   2151:         if ($homeserver ne '') {
                   2152:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2153:             my $host=&hostname($homeserver);
                   2154:             if ($queryid !~/^\Q$host\E\_/) {
                   2155:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2156:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2157:                 return ($outcome,$results);
                   2158:             }
                   2159:             my $response = &get_query_reply($queryid);
                   2160:             my $maxtries = 5;
                   2161:             if ($count > 100) {
                   2162:                 $maxtries = 1+int($count/20);
                   2163:             }
                   2164:             my $tries = 1;
                   2165:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2166:                 $response = &get_query_reply($queryid);
                   2167:                 $tries ++;
                   2168:             }
                   2169:             if ($response eq '') {
                   2170:                 $results = {};
                   2171:                 foreach my $key (keys(%{$users})) {
                   2172:                     my ($uname,$id);
                   2173:                     if ($caller eq 'id') {
                   2174:                         $id = $key;
                   2175:                     } else {
                   2176:                         $uname = $key;
                   2177:                     }
                   2178:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2179:                     $outcome = $resp;
                   2180:                     if ($resp eq 'ok') {
                   2181:                         %{$results} = (%{$results}, %info);
                   2182:                     } else {
                   2183:                         last;
                   2184:                     }
                   2185:                 }
                   2186:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2187:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2188:                     $outcome = $response;
                   2189:                 } else {
                   2190:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2191:                     if ($outcome eq 'ok') {
                   2192:                         $results = &thaw_unescape($userdata);
                   2193:                     }
                   2194:                 }
                   2195:             }
                   2196:         }
                   2197:     }
                   2198:     return ($outcome,$results);
                   2199: }
                   2200: 
1.912     raeburn  2201: sub inst_rulecheck {
1.923     raeburn  2202:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2203:     my %returnhash;
                   2204:     if ($udom ne '') {
                   2205:         if (ref($rules) eq 'ARRAY') {
                   2206:             @{$rules} = map {&escape($_);} (@{$rules});
                   2207:             my $rulestr = join(':',@{$rules});
                   2208:             my $homeserver=&domain($udom,'primary');
                   2209:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2210:                 my $response;
                   2211:                 if ($item eq 'username') {                
                   2212:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2213:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2214:                                               $homeserver));
1.923     raeburn  2215:                 } elsif ($item eq 'id') {
                   2216:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2217:                                               ':'.&escape($id).':'.$rulestr,
                   2218:                                               $homeserver));
1.945     raeburn  2219:                 } elsif ($item eq 'selfcreate') {
                   2220:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2221:                                                &escape($udom).':'.&escape($uname).
                   2222:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2223:                 }
1.912     raeburn  2224:                 if ($response ne 'refused') {
                   2225:                     my @pairs=split(/\&/,$response);
                   2226:                     foreach my $item (@pairs) {
                   2227:                         my ($key,$value)=split(/=/,$item,2);
                   2228:                         $key = &unescape($key);
                   2229:                         next if ($key =~ /^error: 2 /);
                   2230:                         $returnhash{$key}=&thaw_unescape($value);
                   2231:                     }
                   2232:                 }
                   2233:             }
                   2234:         }
                   2235:     }
                   2236:     return %returnhash;
                   2237: }
                   2238: 
                   2239: sub inst_userrules {
1.923     raeburn  2240:     my ($udom,$check) = @_;
1.912     raeburn  2241:     my (%ruleshash,@ruleorder);
                   2242:     if ($udom ne '') {
                   2243:         my $homeserver=&domain($udom,'primary');
                   2244:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2245:             my $response;
                   2246:             if ($check eq 'id') {
                   2247:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2248:                                  $homeserver);
1.943     raeburn  2249:             } elsif ($check eq 'email') {
                   2250:                 $response=&reply('instemailrules:'.&escape($udom),
                   2251:                                  $homeserver);
1.923     raeburn  2252:             } else {
                   2253:                 $response=&reply('instuserrules:'.&escape($udom),
                   2254:                                  $homeserver);
                   2255:             }
1.912     raeburn  2256:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2257:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2258:                 ($response ne 'no_such_host')) {
                   2259:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2260:                 my @pairs=split(/\&/,$hashitems);
                   2261:                 foreach my $item (@pairs) {
                   2262:                     my ($key,$value)=split(/=/,$item,2);
                   2263:                     $key = &unescape($key);
                   2264:                     next if ($key =~ /^error: 2 /);
                   2265:                     $ruleshash{$key}=&thaw_unescape($value);
                   2266:                 }
                   2267:                 my @esc_order = split(/\&/,$orderitems);
                   2268:                 foreach my $item (@esc_order) {
                   2269:                     push(@ruleorder,&unescape($item));
                   2270:                 }
                   2271:             }
                   2272:         }
                   2273:     }
                   2274:     return (\%ruleshash,\@ruleorder);
                   2275: }
                   2276: 
1.976     raeburn  2277: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2278: 
                   2279: sub get_domain_defaults {
1.1172.2.35  raeburn  2280:     my ($domain,$ignore_cache) = @_;
                   2281:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2282:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2283:     unless ($ignore_cache) {
                   2284:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2285:         if (defined($cached)) {
                   2286:             if (ref($result) eq 'HASH') {
                   2287:                 return %{$result};
                   2288:             }
1.943     raeburn  2289:         }
                   2290:     }
                   2291:     my %domdefaults;
                   2292:     my %domconfig =
1.989     raeburn  2293:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2294:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2295:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2296:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2297:                                   'coursecategories','autoenroll',
                   2298:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2299:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2300:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2301:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2302:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2303:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2304:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2305:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2306:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2307:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2308:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2309:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2310:     } else {
                   2311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2314:     }
1.976     raeburn  2315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2318:         } else {
                   2319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2320:         }
1.1172.2.6  raeburn  2321:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2322:         foreach my $item (@usertools) {
                   2323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2325:             }
                   2326:         }
1.1172.2.29  raeburn  2327:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2328:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2329:         }
1.976     raeburn  2330:     }
1.985     raeburn  2331:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2332:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2333:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2334:         }
                   2335:     }
1.1172.2.9  raeburn  2336:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2337:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2338:     }
1.989     raeburn  2339:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2340:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2341:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2342:         }
                   2343:     }
1.1047    raeburn  2344:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2345:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2346:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2347:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2348:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2349:         }
1.1172.2.41  raeburn  2350:         foreach my $type (@coursetypes) {
                   2351:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2352:                 unless ($type eq 'community') {
                   2353:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2354:                 }
                   2355:             }
                   2356:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2357:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2358:             }
1.1172.2.60  raeburn  2359:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2360:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2361:                     $domdefaults{$type.'postsubtimeout'} =
                   2362:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2363:                 }
                   2364:             }
1.1172.2.30  raeburn  2365:         }
1.1172.2.67  raeburn  2366:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2367:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2368:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2369:                 if (@clonecodes) {
                   2370:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2371:                 }
                   2372:             }
                   2373:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2374:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2375:         }
1.1172.2.103  raeburn  2376:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2377:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2378:         }
1.1047    raeburn  2379:     }
1.1073    raeburn  2380:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2381:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2382:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2383:         }
                   2384:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2385:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2386:         }
1.1172.2.62  raeburn  2387:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2388:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2389:         }
1.1073    raeburn  2390:     }
1.1172.2.41  raeburn  2391:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2392:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2393:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2394:                             'approval','limit');
                   2395:             foreach my $type (@coursetypes) {
                   2396:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2397:                     my @mgrdc = ();
                   2398:                     foreach my $item (@settings) {
                   2399:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2400:                             push(@mgrdc,$item);
                   2401:                         }
                   2402:                     }
                   2403:                     if (@mgrdc) {
                   2404:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2405:                     }
                   2406:                 }
                   2407:             }
                   2408:         }
                   2409:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2410:             foreach my $type (@coursetypes) {
                   2411:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2412:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2413:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2414:                     }
                   2415:                 }
                   2416:             }
                   2417:         }
                   2418:     }
1.1172.2.46  raeburn  2419:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2420:         $domdefaults{'catauth'} = 'std';
                   2421:         $domdefaults{'catunauth'} = 'std';
                   2422:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2423:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2424:         }
                   2425:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2426:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2427:         }
                   2428:     }
1.1172.2.76  raeburn  2429:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2430:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2431:     }
1.1172.2.89  raeburn  2432:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2433:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2434:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2435:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2436:         }
                   2437:     }
1.1172.2.23  raeburn  2438:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2439:     return %domdefaults;
                   2440: }
                   2441: 
1.1172.2.106  raeburn  2442: sub get_dom_cats {
                   2443:     my ($dom) = @_;
                   2444:     return unless (&domain($dom));
                   2445:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2446:     unless (defined($cached)) {
                   2447:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2448:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2449:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2450:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2451:             } else {
                   2452:                 $cats = {};
                   2453:             }
                   2454:         } else {
                   2455:             $cats = {};
                   2456:         }
                   2457:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2458:     }
                   2459:     return $cats;
                   2460: }
                   2461: 
                   2462: sub get_dom_instcats {
                   2463:     my ($dom) = @_;
                   2464:     return unless (&domain($dom));
                   2465:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2466:     unless (defined($cached)) {
                   2467:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2468:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2469:         if ($totcodes > 0) {
                   2470:             my $caller = 'global';
                   2471:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2472:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2473:                 $instcats = {
                   2474:                                 codes => \%codes,
                   2475:                                 codetitles => \@codetitles,
                   2476:                                 cat_titles => \%cat_titles,
                   2477:                                 cat_order => \%cat_order,
                   2478:                             };
                   2479:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2480:             }
                   2481:         }
                   2482:     }
                   2483:     return $instcats;
                   2484: }
                   2485: 
                   2486: sub retrieve_instcodes {
                   2487:     my ($coursecodes,$dom) = @_;
                   2488:     my $totcodes;
                   2489:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2490:     foreach my $course (keys(%courses)) {
                   2491:         if (ref($courses{$course}) eq 'HASH') {
                   2492:             if ($courses{$course}{'inst_code'} ne '') {
                   2493:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2494:                 $totcodes ++;
                   2495:             }
                   2496:         }
                   2497:     }
                   2498:     return $totcodes;
                   2499: }
                   2500: 
1.1172.2.113  raeburn  2501: # --------------------------------------------- Get domain config for passwords
                   2502: 
                   2503: sub get_passwdconf {
                   2504:     my ($dom) = @_;
                   2505:     my (%passwdconf,$gotconf,$lookup);
                   2506:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2507:     if (defined($cached)) {
                   2508:         if (ref($result) eq 'HASH') {
                   2509:             %passwdconf = %{$result};
                   2510:             $gotconf = 1;
                   2511:         }
                   2512:     }
                   2513:     unless ($gotconf) {
                   2514:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2515:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2516:             %passwdconf = %{$domconfig{'passwords'}};
                   2517:         }
                   2518:         my $cachetime = 24*60*60;
                   2519:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2520:     }
                   2521:     return %passwdconf;
                   2522: }
                   2523: 
1.1172.2.118.  .1(raebu 2524:20): sub course_portal_url {
                   2525:20):     my ($cnum,$cdom) = @_;
                   2526:20):     my $chome = &homeserver($cnum,$cdom);
                   2527:20):     my $hostname = &hostname($chome);
                   2528:20):     my $protocol = $protocol{$chome};
                   2529:20):     $protocol = 'http' if ($protocol ne 'https');
                   2530:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2531:20):     my $firsturl;
                   2532:20):     if ($domdefaults{'portal_def'}) {
                   2533:20):         $firsturl = $domdefaults{'portal_def'};
                   2534:20):     } else {
                   2535:20):         $firsturl = $protocol.'://'.$hostname;
                   2536:20):     }
                   2537:20):     return $firsturl;
                   2538:20): }
                   2539:20): 
1.344     www      2540: # --------------------------------------------------- Assign a key to a student
                   2541: 
                   2542: sub assign_access_key {
1.364     www      2543: #
                   2544: # a valid key looks like uname:udom#comments
                   2545: # comments are being appended
                   2546: #
1.498     www      2547:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2548:     $kdom=
1.620     albertel 2549:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2550:     $knum=
1.620     albertel 2551:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2552:     $cdom=
1.620     albertel 2553:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2554:     $cnum=
1.620     albertel 2555:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2556:     $udom=$env{'user.name'} unless (defined($udom));
                   2557:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2558:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2559:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2560:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2561:                                                   # assigned to this person
                   2562:                                                   # - this should not happen,
1.345     www      2563:                                                   # unless something went wrong
                   2564:                                                   # the first time around
                   2565: # ready to assign
1.364     www      2566:         $logentry=$1.'; '.$logentry;
1.496     www      2567:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2568:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2569: # key now belongs to user
1.346     www      2570: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2571:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2572:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2573:                 return 'ok';
                   2574:             } else {
                   2575:                 return 
                   2576:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2577: 	    }
                   2578:         } else {
                   2579:             return 'error: Could not assign key, try again later.';
                   2580:         }
1.364     www      2581:     } elsif (!$existing{$ckey}) {
1.345     www      2582: # the key does not exist
                   2583: 	return 'error: The key does not exist';
                   2584:     } else {
                   2585: # the key is somebody else's
                   2586: 	return 'error: The key is already in use';
                   2587:     }
1.344     www      2588: }
                   2589: 
1.364     www      2590: # ------------------------------------------ put an additional comment on a key
                   2591: 
                   2592: sub comment_access_key {
                   2593: #
                   2594: # a valid key looks like uname:udom#comments
                   2595: # comments are being appended
                   2596: #
                   2597:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2598:     $cdom=
1.620     albertel 2599:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2600:     $cnum=
1.620     albertel 2601:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2602:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2603:     if ($existing{$ckey}) {
                   2604:         $existing{$ckey}.='; '.$logentry;
                   2605: # ready to assign
1.367     www      2606:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2607:                                                  $cdom,$cnum) eq 'ok') {
                   2608: 	    return 'ok';
                   2609:         } else {
                   2610: 	    return 'error: Count not store comment.';
                   2611:         }
                   2612:     } else {
                   2613: # the key does not exist
                   2614: 	return 'error: The key does not exist';
                   2615:     }
                   2616: }
                   2617: 
1.344     www      2618: # ------------------------------------------------------ Generate a set of keys
                   2619: 
                   2620: sub generate_access_keys {
1.364     www      2621:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2622:     $cdom=
1.620     albertel 2623:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2624:     $cnum=
1.620     albertel 2625:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2626:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2627:     unless (($cdom) && ($cnum)) { return 0; }
                   2628:     if ($number>10000) { return 0; }
                   2629:     sleep(2); # make sure don't get same seed twice
                   2630:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2631:     my $total=0;
                   2632:     for (my $i=1;$i<=$number;$i++) {
                   2633:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2634:                   sprintf("%lx",int(100000*rand)).'-'.
                   2635:                   sprintf("%lx",int(100000*rand));
                   2636:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2637:        $newkey=~s/0/h/g; # and also 0 and O
                   2638:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2639:        if ($existing{$newkey}) {
                   2640:            $i--;
                   2641:        } else {
1.364     www      2642: 	  if (&put('accesskeys',
                   2643:               { $newkey => '# generated '.localtime().
1.620     albertel 2644:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2645:                            '; '.$logentry },
                   2646: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2647:               $total++;
                   2648: 	  }
                   2649:        }
                   2650:     }
1.620     albertel 2651:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2652:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2653:     return $total;
                   2654: }
                   2655: 
                   2656: # ------------------------------------------------------- Validate an accesskey
                   2657: 
                   2658: sub validate_access_key {
                   2659:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2660:     $cdom=
1.620     albertel 2661:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2662:     $cnum=
1.620     albertel 2663:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2664:     $udom=$env{'user.domain'} unless (defined($udom));
                   2665:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2666:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2667:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2668: }
                   2669: 
                   2670: # ------------------------------------- Find the section of student in a course
1.652     albertel 2671: sub devalidate_getsection_cache {
                   2672:     my ($udom,$unam,$courseid)=@_;
                   2673:     my $hashid="$udom:$unam:$courseid";
                   2674:     &devalidate_cache_new('getsection',$hashid);
                   2675: }
1.298     matthew  2676: 
1.815     albertel 2677: sub courseid_to_courseurl {
                   2678:     my ($courseid) = @_;
                   2679:     #already url style courseid
                   2680:     return $courseid if ($courseid =~ m{^/});
                   2681: 
                   2682:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2683: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2684: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2685: 	return "/$cdom/$cnum";
                   2686:     }
                   2687: 
                   2688:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2689:     if (exists($courseinfo{'num'})) {
                   2690: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2691:     }
                   2692: 
                   2693:     return undef;
                   2694: }
                   2695: 
1.298     matthew  2696: sub getsection {
                   2697:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2698:     my $cachetime=1800;
1.551     albertel 2699: 
                   2700:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2701:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2702:     if (defined($cached)) { return $result; }
                   2703: 
1.298     matthew  2704:     my %Pending; 
                   2705:     my %Expired;
                   2706:     #
                   2707:     # Each role can either have not started yet (pending), be active, 
                   2708:     #    or have expired.
                   2709:     #
                   2710:     # If there is an active role, we are done.
                   2711:     #
                   2712:     # If there is more than one role which has not started yet, 
                   2713:     #     choose the one which will start sooner
                   2714:     # If there is one role which has not started yet, return it.
                   2715:     #
                   2716:     # If there is more than one expired role, choose the one which ended last.
                   2717:     # If there is a role which has expired, return it.
                   2718:     #
1.815     albertel 2719:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2720:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2721:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2722:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2723:         my $section=$1;
                   2724:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2725:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2726:         my $now=time;
1.548     albertel 2727:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2728:             $Expired{$end}=$section;
                   2729:             next;
                   2730:         }
1.548     albertel 2731:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2732:             $Pending{$start}=$section;
                   2733:             next;
                   2734:         }
1.599     albertel 2735:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2736:     }
                   2737:     #
                   2738:     # Presumedly there will be few matching roles from the above
                   2739:     # loop and the sorting time will be negligible.
                   2740:     if (scalar(keys(%Pending))) {
                   2741:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2742:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2743:     } 
                   2744:     if (scalar(keys(%Expired))) {
                   2745:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2746:         my $time = pop(@sorted);
1.599     albertel 2747:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2748:     }
1.599     albertel 2749:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2750: }
1.70      www      2751: 
1.599     albertel 2752: sub save_cache {
                   2753:     &purge_remembered();
1.722     albertel 2754:     #&Apache::loncommon::validate_page();
1.620     albertel 2755:     undef(%env);
1.780     albertel 2756:     undef($env_loaded);
1.599     albertel 2757: }
1.452     albertel 2758: 
1.599     albertel 2759: my $to_remember=-1;
                   2760: my %remembered;
                   2761: my %accessed;
                   2762: my $kicks=0;
                   2763: my $hits=0;
1.849     albertel 2764: sub make_key {
                   2765:     my ($name,$id) = @_;
1.872     albertel 2766:     if (length($id) > 65 
                   2767: 	&& length(&escape($id)) > 200) {
                   2768: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2769:     }
1.849     albertel 2770:     return &escape($name.':'.$id);
                   2771: }
                   2772: 
1.599     albertel 2773: sub devalidate_cache_new {
                   2774:     my ($name,$id,$debug) = @_;
                   2775:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2776:     my $remembered_id=$name.':'.$id;
1.849     albertel 2777:     $id=&make_key($name,$id);
1.599     albertel 2778:     $memcache->delete($id);
1.1172.2.81  raeburn  2779:     delete($remembered{$remembered_id});
                   2780:     delete($accessed{$remembered_id});
1.599     albertel 2781: }
                   2782: 
                   2783: sub is_cached_new {
                   2784:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2785:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2786:                                      # keys in %remembered hash, which persists for
                   2787:                                      # duration of request (no restriction on key length).
                   2788:     if (exists($remembered{$remembered_id})) {
                   2789: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2790: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2791: 	$hits++;
1.1172.2.81  raeburn  2792: 	return ($remembered{$remembered_id},1);
1.599     albertel 2793:     }
1.1172.2.81  raeburn  2794:     $id=&make_key($name,$id);
1.599     albertel 2795:     my $value = $memcache->get($id);
                   2796:     if (!(defined($value))) {
                   2797: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2798: 	return (undef,undef);
1.416     albertel 2799:     }
1.599     albertel 2800:     if ($value eq '__undef__') {
                   2801: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2802: 	$value=undef;
                   2803:     }
1.1172.2.81  raeburn  2804:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2805:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2806:     return ($value,1);
                   2807: }
                   2808: 
                   2809: sub do_cache_new {
                   2810:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2811:     my $remembered_id=$name.':'.$id;
1.849     albertel 2812:     $id=&make_key($name,$id);
1.599     albertel 2813:     my $setvalue=$value;
                   2814:     if (!defined($setvalue)) {
                   2815: 	$setvalue='__undef__';
                   2816:     }
1.623     albertel 2817:     if (!defined($time) ) {
                   2818: 	$time=600;
                   2819:     }
1.599     albertel 2820:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2821:     my $result = $memcache->set($id,$setvalue,$time);
                   2822:     if (! $result) {
1.872     albertel 2823: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2824: 	$memcache->disconnect_all();
1.872     albertel 2825:     }
1.600     albertel 2826:     # need to make a copy of $value
1.1172.2.81  raeburn  2827:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2828:     return $value;
                   2829: }
                   2830: 
                   2831: sub make_room {
1.1172.2.81  raeburn  2832:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2833: 
1.1172.2.81  raeburn  2834:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2835:                                     : $value;
1.599     albertel 2836:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2837:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2838:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2839:     my $to_kick;
                   2840:     my $max_time=0;
                   2841:     foreach my $other (keys(%accessed)) {
                   2842: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2843: 	    $to_kick=$other;
                   2844: 	    $max_time=&tv_interval($accessed{$other});
                   2845: 	}
                   2846:     }
                   2847:     delete($remembered{$to_kick});
                   2848:     delete($accessed{$to_kick});
                   2849:     $kicks++;
                   2850:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2851:     return;
                   2852: }
                   2853: 
1.599     albertel 2854: sub purge_remembered {
1.604     albertel 2855:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2856:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2857:     undef(%remembered);
                   2858:     undef(%accessed);
1.428     albertel 2859: }
1.70      www      2860: # ------------------------------------- Read an entry from a user's environment
                   2861: 
                   2862: sub userenvironment {
                   2863:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2864:     my $items;
                   2865:     foreach my $item (@what) {
                   2866:         $items.=&escape($item).'&';
                   2867:     }
                   2868:     $items=~s/\&$//;
1.70      www      2869:     my %returnhash=();
1.1009    raeburn  2870:     my $uhome = &homeserver($unam,$udom);
                   2871:     unless ($uhome eq 'no_host') {
                   2872:         my @answer=split(/\&/, 
                   2873:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2874:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2875:             return %returnhash;
                   2876:         }
1.1009    raeburn  2877:         my $i;
                   2878:         for ($i=0;$i<=$#what;$i++) {
                   2879: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2880:         }
1.70      www      2881:     }
                   2882:     return %returnhash;
1.1       albertel 2883: }
                   2884: 
1.617     albertel 2885: # ---------------------------------------------------------- Get a studentphoto
                   2886: sub studentphoto {
                   2887:     my ($udom,$unam,$ext) = @_;
                   2888:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2889:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2890:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2891:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2892:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2893:             } else {
                   2894:                 my ($result,$perm_reqd)=
1.707     albertel 2895: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2896:                 if ($result eq 'ok') {
                   2897:                     if (!($perm_reqd eq 'yes')) {
                   2898:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2899:                     }
                   2900:                 }
                   2901:             }
                   2902:         }
                   2903:     } else {
                   2904:         my ($result,$perm_reqd) = 
1.707     albertel 2905: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2906:         if ($result eq 'ok') {
                   2907:             if (!($perm_reqd eq 'yes')) {
                   2908:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2909:             }
                   2910:         }
                   2911:     }
                   2912:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2913: }
                   2914: 
                   2915: sub retrievestudentphoto {
                   2916:     my ($udom,$unam,$ext,$type) = @_;
                   2917:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2918:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2919:     if ($ret eq 'ok') {
                   2920:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2921:         if ($type eq 'thumbnail') {
                   2922:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2923:         }
                   2924:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2925:         return $tokenurl;
                   2926:     } else {
                   2927:         if ($type eq 'thumbnail') {
                   2928:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2929:         } else { 
                   2930:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2931:         }
1.617     albertel 2932:     }
                   2933: }
                   2934: 
1.263     www      2935: # -------------------------------------------------------------------- New chat
                   2936: 
                   2937: sub chatsend {
1.724     raeburn  2938:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2939:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2940:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2941:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2942:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2943: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2944: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2945: }
                   2946: 
                   2947: # ------------------------------------------ Find current version of a resource
                   2948: 
                   2949: sub getversion {
                   2950:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2951:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2952:     return &currentversion(&filelocation('',$fname));
                   2953: }
                   2954: 
                   2955: sub currentversion {
                   2956:     my $fname=shift;
                   2957:     my $author=$fname;
                   2958:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2959:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2960:     my $home=&homeserver($uname,$udom);
1.292     www      2961:     if ($home eq 'no_host') { 
                   2962:         return -1; 
                   2963:     }
1.1112    www      2964:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2965:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2966: 	return -1;
                   2967:     }
1.1112    www      2968:     return $answer;
1.263     www      2969: }
                   2970: 
1.1111    www      2971: #
                   2972: # Return special version number of resource if set by override, empty otherwise
                   2973: #
                   2974: sub usedversion {
                   2975:     my $fname=shift;
                   2976:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2977:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2978:     if ($urlversion) { return $urlversion; }
                   2979:     return '';
                   2980: }
                   2981: 
1.1       albertel 2982: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2983: 
1.1       albertel 2984: sub subscribe {
                   2985:     my $fname=shift;
1.761     raeburn  2986:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2987:     $fname=~s/[\n\r]//g;
1.1       albertel 2988:     my $author=$fname;
                   2989:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2990:     my ($udom,$uname)=split(/\//,$author);
                   2991:     my $home=homeserver($uname,$udom);
1.335     albertel 2992:     if ($home eq 'no_host') {
                   2993:         return 'not_found';
1.1       albertel 2994:     }
                   2995:     my $answer=reply("sub:$fname",$home);
1.64      www      2996:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2997: 	$answer.=' by '.$home;
                   2998:     }
1.1       albertel 2999:     return $answer;
                   3000: }
                   3001:     
1.8       www      3002: # -------------------------------------------------------------- Replicate file
                   3003: 
                   3004: sub repcopy {
                   3005:     my $filename=shift;
1.23      www      3006:     $filename=~s/\/+/\//g;
1.1142    raeburn  3007:     my $londocroot = $perlvar{'lonDocRoot'};
                   3008:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3009:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3010:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3011: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3012: 	return &repcopy_userfile($filename);
                   3013:     }
1.532     albertel 3014:     $filename=~s/[\n\r]//g;
1.8       www      3015:     my $transname="$filename.in.transfer";
1.828     www      3016: # FIXME: this should flock
1.607     raeburn  3017:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3018:     my $remoteurl=subscribe($filename);
1.64      www      3019:     if ($remoteurl =~ /^con_lost by/) {
                   3020: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3021:            return 'unavailable';
1.8       www      3022:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3023: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3024: 	   return 'not_found';
1.64      www      3025:     } elsif ($remoteurl =~ /^rejected by/) {
                   3026: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3027:            return 'forbidden';
1.20      www      3028:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3029:            return 'ok';
1.8       www      3030:     } else {
1.290     www      3031:         my $author=$filename;
                   3032:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3033:         my ($udom,$uname)=split(/\//,$author);
                   3034:         my $home=homeserver($uname,$udom);
                   3035:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3036:            my @parts=split(/\//,$filename);
                   3037:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3038:            if ($path ne "$londocroot/res") {
1.8       www      3039:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3040: 	       return 'bad_request';
1.8       www      3041:            }
                   3042:            my $count;
                   3043:            for ($count=5;$count<$#parts;$count++) {
                   3044:                $path.="/$parts[$count]";
                   3045:                if ((-e $path)!=1) {
                   3046: 		   mkdir($path,0777);
                   3047:                }
                   3048:            }
                   3049:            my $ua=new LWP::UserAgent;
                   3050:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3051:            my $response=$ua->request($request,$transname);
                   3052:            if ($response->is_error()) {
                   3053: 	       unlink($transname);
                   3054:                my $message=$response->status_line;
1.672     albertel 3055:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3056:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3057:                return 'unavailable';
1.8       www      3058:            } else {
1.16      www      3059: 	       if ($remoteurl!~/\.meta$/) {
                   3060:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3061:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3062:                   if ($mresponse->is_error()) {
                   3063: 		      unlink($filename.'.meta');
                   3064:                       &logthis(
1.672     albertel 3065:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3066:                   }
                   3067: 	       }
1.8       www      3068:                rename($transname,$filename);
1.607     raeburn  3069:                return 'ok';
1.8       www      3070:            }
1.290     www      3071:        }
1.8       www      3072:     }
1.330     www      3073: }
                   3074: 
                   3075: # ------------------------------------------------ Get server side include body
                   3076: sub ssi_body {
1.381     albertel 3077:     my ($filelink,%form)=@_;
1.606     matthew  3078:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3079:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3080:     }
1.953     www      3081:     my $output='';
                   3082:     my $response;
1.980     raeburn  3083:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3084:        ($output,$response)=&externalssi($filelink);
1.953     www      3085:     } else {
1.1004    droeschl 3086:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3087:        $filelink .= 'inhibitmenu=yes';
1.953     www      3088:        ($output,$response)=&ssi($filelink,%form);
                   3089:     }
1.778     albertel 3090:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3091:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3092:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3093:     if (wantarray) {
                   3094:         return ($output, $response);
                   3095:     } else {
                   3096:         return $output;
                   3097:     }
1.8       www      3098: }
                   3099: 
1.15      www      3100: # --------------------------------------------------------- Server Side Include
                   3101: 
1.782     albertel 3102: sub absolute_url {
                   3103:     my ($host_name) = @_;
                   3104:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3105:     if ($host_name eq '') {
                   3106: 	$host_name = $ENV{'SERVER_NAME'};
                   3107:     }
                   3108:     return $protocol.$host_name;
                   3109: }
                   3110: 
1.942     foxr     3111: #
                   3112: #   Server side include.
                   3113: # Parameters:
                   3114: #  fn     Possibly encrypted resource name/id.
                   3115: #  form   Hash that describes how the rendering should be done
                   3116: #         and other things.
1.944     foxr     3117: # Returns:
1.950     raeburn  3118: #   Scalar context: The content of the response.
                   3119: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3120: #     
1.15      www      3121: sub ssi {
                   3122: 
1.944     foxr     3123:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3124:     my ($request,$response);
1.711     albertel 3125: 
                   3126:     $form{'no_update_last_known'}=1;
1.895     albertel 3127:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3128:     if (%form) {
1.782     albertel 3129:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3130:       $request->content(join('&',map {
                   3131:             my $name = escape($_);
                   3132:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3133:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3134:             : &escape($form{$_}) );
                   3135:         } keys(%form)));
1.23      www      3136:     } else {
1.782     albertel 3137:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3138:     }
                   3139: 
1.15      www      3140:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3141: 
1.1172.2.101  raeburn  3142:     if (($env{'request.course.id'}) &&
                   3143:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3144:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3145:         ($form{'grade_symb'} ne '') &&
                   3146:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3147:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3148:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3149:             my $ua=new LWP::UserAgent;
                   3150:             $ua->local_address('127.0.0.1');
                   3151:             $response = $ua->request($request);
                   3152:         } else {
                   3153:             {
                   3154:                 require LWP::Protocol::http;
                   3155:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3156:                 my $ua=new LWP::UserAgent;
                   3157:                 $response = $ua->request($request);
                   3158:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3159:             }
                   3160:         }
                   3161:     } else {
                   3162:         my $ua=new LWP::UserAgent;
                   3163:         $response = $ua->request($request);
                   3164:     }
1.944     foxr     3165:     if (wantarray) {
1.1172.2.3  raeburn  3166: 	return ($response->content, $response);
1.944     foxr     3167:     } else {
1.1172.2.3  raeburn  3168: 	return $response->content;
1.942     foxr     3169:     }
1.324     www      3170: }
                   3171: 
                   3172: sub externalssi {
                   3173:     my ($url)=@_;
                   3174:     my $ua=new LWP::UserAgent;
                   3175:     my $request=new HTTP::Request('GET',$url);
                   3176:     my $response=$ua->request($request);
1.954     raeburn  3177:     if (wantarray) {
                   3178:         return ($response->content, $response);
                   3179:     } else {
                   3180:         return $response->content;
                   3181:     }
1.15      www      3182: }
1.254     www      3183: 
1.1172.2.98  raeburn  3184: # If the local copy of a replicated resource is outdated, trigger a
                   3185: # connection from the homeserver to flush the delayed queue. If no update
                   3186: # happens, remove local copies of outdated resource (and corresponding
                   3187: # metadata file).
                   3188: 
                   3189: sub remove_stale_resfile {
                   3190:     my ($url) = @_;
                   3191:     my $removed;
                   3192:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3193:         my $audom = $1;
                   3194:         my $auname = $2;
                   3195:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3196:             my $homeserver = &homeserver($auname,$audom);
                   3197:             unless (($homeserver eq 'no_host') ||
                   3198:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3199:                 my $fname = &filelocation('',$url);
                   3200:                 if (-e $fname) {
                   3201:                     my $hostname = &hostname($homeserver);
                   3202:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3203:20):                         my $protocol = $protocol{$homeserver};
                   3204:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3205:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3206:20):                         my $ua=new LWP::UserAgent;
                   3207:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3208:                         my $request=new HTTP::Request('HEAD',$uri);
                   3209:                         my $response=$ua->request($request);
                   3210:                         if ($response->is_success()) {
                   3211:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3212:                             my $locmodtime = (stat($fname))[9];
                   3213:                             if ($locmodtime < $remmodtime) {
                   3214:                                 my $stale;
                   3215:                                 my $answer = &reply('pong',$homeserver);
                   3216:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3217:                                     sleep(0.2);
                   3218:                                     $locmodtime = (stat($fname))[9];
                   3219:                                     if ($locmodtime < $remmodtime) {
                   3220:                                         my $posstransfer = $fname.'.in.transfer';
                   3221:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3222:                                             $removed = 1;
                   3223:                                         } else {
                   3224:                                             $stale = 1;
                   3225:                                         }
                   3226:                                     } else {
                   3227:                                         $removed = 1;
                   3228:                                     }
                   3229:                                 } else {
                   3230:                                     $stale = 1;
                   3231:                                 }
                   3232:                                 if ($stale) {
                   3233:                                     unlink($fname);
                   3234:                                     if ($uri!~/\.meta$/) {
                   3235:                                         unlink($fname.'.meta');
                   3236:                                     }
                   3237:                                     &reply("unsub:$fname",$homeserver);
                   3238:                                     $removed = 1;
                   3239:                                 }
                   3240:                             }
                   3241:                         }
                   3242:                     }
                   3243:                 }
                   3244:             }
                   3245:         }
                   3246:     }
                   3247:     return $removed;
                   3248: }
                   3249: 
1.492     albertel 3250: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3251: 
                   3252: sub allowuploaded {
                   3253:     my ($srcurl,$url)=@_;
                   3254:     $url=&clutter(&declutter($url));
                   3255:     my $dir=$url;
                   3256:     $dir=~s/\/[^\/]+$//;
                   3257:     my %httpref=();
                   3258:     my $httpurl=&hreflocation('',$url);
                   3259:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3260:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3261: }
1.477     raeburn  3262: 
1.1172.2.13  raeburn  3263: #
                   3264: # Determine if the current user should be able to edit a particular resource,
                   3265: # when viewing in course context.
                   3266: # (a) When viewing resource used to determine if "Edit" item is included in
                   3267: #     Functions.
                   3268: # (b) When displaying folder contents in course editor, used to determine if
                   3269: #     "Edit" link will be displayed alongside resource.
                   3270: #
                   3271: #  input: six args -- filename (decluttered), course number, course domain,
                   3272: #                   url, symb (if registered) and group (if this is a group
                   3273: #                   item -- e.g., bulletin board, group page etc.).
                   3274: #  output: array of five scalars --
                   3275: #          $cfile -- url for file editing if editable on current server
                   3276: #          $home -- homeserver of resource (i.e., for author if published,
                   3277: #                                           or course if uploaded.).
                   3278: #          $switchserver --  1 if server switch will be needed.
                   3279: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3280: #          $forceview -- 1 if icon/link should be to go to view mode
                   3281: #
                   3282: 
                   3283: sub can_edit_resource {
                   3284:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3285:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3286: #
                   3287: # For aboutme pages user can only edit his/her own.
                   3288: #
                   3289:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3290:         my ($sdom,$sname) = ($1,$2);
                   3291:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3292:             $home = $env{'user.home'};
                   3293:             $cfile = $resurl;
                   3294:             if ($env{'form.forceedit'}) {
                   3295:                 $forceview = 1;
                   3296:             } else {
                   3297:                 $forceedit = 1;
                   3298:             }
                   3299:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3300:         } else {
                   3301:             return;
                   3302:         }
                   3303:     }
                   3304: 
                   3305:     if ($env{'request.course.id'}) {
                   3306:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3307:         if ($group ne '') {
                   3308: # if this is a group homepage or group bulletin board, check group privs
                   3309:             my $allowed = 0;
                   3310:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3311:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3312:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3313:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3314:                     $allowed = 1;
                   3315:                 }
                   3316:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3317:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3318:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3319:                     $allowed = 1;
                   3320:                 }
                   3321:             }
                   3322:             if ($allowed) {
                   3323:                 $home=&homeserver($cnum,$cdom);
                   3324:                 if ($env{'form.forceedit'}) {
                   3325:                     $forceview = 1;
                   3326:                 } else {
                   3327:                     $forceedit = 1;
                   3328:                 }
                   3329:                 $cfile = $resurl;
                   3330:             } else {
                   3331:                 return;
                   3332:             }
                   3333:         } else {
1.1172.2.15  raeburn  3334:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3335:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3336:                     return;
                   3337:                 }
                   3338:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3339: #
                   3340: # No edit allowed where CC has switched to student role.
                   3341: #
                   3342:                 return;
                   3343:             }
                   3344:         }
                   3345:     }
                   3346: 
                   3347:     if ($file ne '') {
                   3348:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3349:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3350:                 $uploaded = 1;
                   3351:                 $incourse = 1;
                   3352:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3353:                     $cfile = &hreflocation('',$file);
                   3354:                     if ($env{'form.forceedit'}) {
                   3355:                         $forceview = 1;
                   3356:                     } else {
                   3357:                         $forceedit = 1;
                   3358:                     }
                   3359:                 }
                   3360:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3361:                 $incourse = 1;
                   3362:                 if ($env{'form.forceedit'}) {
                   3363:                     $forceview = 1;
                   3364:                 } else {
                   3365:                     $forceedit = 1;
                   3366:                 }
                   3367:                 $cfile = $resurl;
                   3368:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3369:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3370:                     $incourse = 1;
                   3371:                     if ($env{'form.forceedit'}) {
                   3372:                         $forceview = 1;
                   3373:                     } else {
                   3374:                         $forceedit = 1;
                   3375:                     }
                   3376:                     $cfile = $resurl;
                   3377:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3378:                     $incourse = 1;
                   3379:                     $cfile = $resurl.'/smpedit';
                   3380:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3381:                     $incourse = 1;
                   3382:                     if ($env{'form.forceedit'}) {
                   3383:                         $forceview = 1;
                   3384:                     } else {
                   3385:                         $forceedit = 1;
                   3386:                     }
                   3387:                     $cfile = $resurl;
1.1172.2.118.  .1(raebu 3388:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3389:20):                     $incourse = 1;
                   3390:20):                     if ($env{'form.forceedit'}) {
                   3391:20):                         $forceview = 1;
                   3392:20):                     } else {
                   3393:20):                         $forceedit = 1;
                   3394:20):                     }
                   3395:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3396:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3397:                     $incourse = 1;
                   3398:                     if ($env{'form.forceedit'}) {
                   3399:                         $forceview = 1;
                   3400:                     } else {
                   3401:                         $forceedit = 1;
                   3402:                     }
                   3403:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3404:                 }
                   3405:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3406:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3407:                 if (&is_on_map($template)) {
                   3408:                     $incourse = 1;
                   3409:                     $forceview = 1;
                   3410:                     $cfile = $template;
                   3411:                 }
                   3412:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3413:                 $incourse = 1;
                   3414:                 if ($env{'form.forceedit'}) {
                   3415:                     $forceview = 1;
                   3416:                 } else {
                   3417:                     $forceedit = 1;
                   3418:                 }
                   3419:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3420:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3421:20):                 $incourse = 1;
                   3422:20):                 if ($env{'form.forceedit'}) {
                   3423:20):                     $forceview = 1;
                   3424:20):                 } else {
                   3425:20):                     $forceedit = 1;
                   3426:20):                 }
                   3427:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3428:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3429:                 $incourse = 1;
                   3430:                 $forceview = 1;
                   3431:                 if ($symb) {
                   3432:                     my ($map,$id,$res)=&decode_symb($symb);
                   3433:                     $env{'request.symb'} = $symb;
                   3434:                     $cfile = &clutter($res);
                   3435:                 } else {
                   3436:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3437:20):                     my $escfile = &unescape($cfile);
                   3438:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3439:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3440:20):                     } else {
                   3441:20):                         $escfile =~ s{^http://}{};
                   3442:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3443:20):                     }
1.1172.2.13  raeburn  3444:                 }
1.1172.2.31  raeburn  3445:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3446:                 if ($env{'form.forceedit'}) {
                   3447:                     $forceview = 1;
                   3448:                 } else {
                   3449:                     $forceedit = 1;
                   3450:                 }
                   3451:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3452:             }
                   3453:         }
                   3454:         if ($uploaded || $incourse) {
                   3455:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3456:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3457:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3458:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3459:             # Check that the user has permission to edit this resource
                   3460:             my $setpriv = 1;
                   3461:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3462:             if (defined($cfudom)) {
                   3463:                 $home=&homeserver($cfuname,$cfudom);
                   3464:                 $cfile=$file;
                   3465:             }
                   3466:         }
                   3467:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3468:             (($home ne '') && ($home ne 'no_host'))) {
                   3469:             my @ids=&current_machine_ids();
                   3470:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3471:                 $switchserver=1;
                   3472:             }
                   3473:         }
                   3474:     }
                   3475:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3476: }
                   3477: 
                   3478: sub is_course_upload {
                   3479:     my ($file,$cnum,$cdom) = @_;
                   3480:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3481:     $uploadpath =~ s{^\/}{};
                   3482:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3483:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3484:         return 1;
                   3485:     }
                   3486:     return;
                   3487: }
                   3488: 
                   3489: sub in_course {
                   3490:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3491:     if ($hideprivileged) {
                   3492:         my $skipuser;
1.1172.2.23  raeburn  3493:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3494:         my @possdoms = ($cdom);
                   3495:         if ($coursehash{'checkforpriv'}) {
                   3496:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3497:         }
                   3498:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3499:             $skipuser = 1;
                   3500:             if ($coursehash{'nothideprivileged'}) {
                   3501:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3502:                     my $user;
                   3503:                     if ($item =~ /:/) {
                   3504:                         $user = $item;
                   3505:                     } else {
                   3506:                         $user = join(':',split(/[\@]/,$item));
                   3507:                     }
                   3508:                     if ($user eq $uname.':'.$udom) {
                   3509:                         undef($skipuser);
                   3510:                         last;
                   3511:                     }
                   3512:                 }
                   3513:             }
                   3514:             if ($skipuser) {
                   3515:                 return 0;
                   3516:             }
                   3517:         }
                   3518:     }
                   3519:     $type ||= 'any';
                   3520:     if (!defined($cdom) || !defined($cnum)) {
                   3521:         my $cid  = $env{'request.course.id'};
                   3522:         $cdom = $env{'course.'.$cid.'.domain'};
                   3523:         $cnum = $env{'course.'.$cid.'.num'};
                   3524:     }
                   3525:     my $typesref;
                   3526:     if (($type eq 'any') || ($type eq 'all')) {
                   3527:         $typesref = ['active','previous','future'];
                   3528:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3529:         $typesref = [$type];
                   3530:     }
                   3531:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3532:                               $typesref,undef,[$cdom]);
                   3533:     my ($tmp) = keys(%roles);
                   3534:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3535:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3536:     if (@course_roles > 0) {
                   3537:         return 1;
                   3538:     }
                   3539:     return 0;
                   3540: }
                   3541: 
1.478     albertel 3542: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3543: # input: action, courseID, current domain, intended
1.637     raeburn  3544: #        path to file, source of file, instruction to parse file for objects,
                   3545: #        ref to hash for embedded objects,
                   3546: #        ref to hash for codebase of java objects.
1.1095    raeburn  3547: #        reference to scalar to accommodate mime type determined
                   3548: #          from File::MMagic if $parser = parse.
1.637     raeburn  3549: #
1.485     raeburn  3550: # output: url to file (if action was uploaddoc), 
                   3551: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3552: #
1.478     albertel 3553: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3554: # course.
1.477     raeburn  3555: #
1.478     albertel 3556: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3557: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3558: #          course's home server.
1.477     raeburn  3559: #
1.478     albertel 3560: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3561: #          be copied from $source (current location) to 
                   3562: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3563: #         and will then be copied to
                   3564: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3565: #         course's home server.
1.485     raeburn  3566: #
1.481     raeburn  3567: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3568: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3569: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3570: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3571: #         in course's home server.
1.637     raeburn  3572: #
1.477     raeburn  3573: 
                   3574: sub process_coursefile {
1.1095    raeburn  3575:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3576:         $mimetype)=@_;
1.477     raeburn  3577:     my $fetchresult;
1.638     albertel 3578:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3579:     if ($action eq 'propagate') {
1.638     albertel 3580:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3581: 			     $home);
1.481     raeburn  3582:     } else {
1.477     raeburn  3583:         my $fpath = '';
                   3584:         my $fname = $file;
1.478     albertel 3585:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3586:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3587:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3588:         if ($action eq 'copy') {
                   3589:             if ($source eq '') {
                   3590:                 $fetchresult = 'no source file';
                   3591:                 return $fetchresult;
                   3592:             } else {
                   3593:                 my $destination = $filepath.'/'.$fname;
                   3594:                 rename($source,$destination);
                   3595:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3596:                                  $home);
1.481     raeburn  3597:             }
                   3598:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3599:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3600:             print $fh $env{'form.'.$source};
1.481     raeburn  3601:             close($fh);
1.637     raeburn  3602:             if ($parser eq 'parse') {
1.1024    raeburn  3603:                 my $mm = new File::MMagic;
1.1095    raeburn  3604:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3605:                 if ($type eq 'text/html') {
1.1024    raeburn  3606:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3607:                     unless ($parse_result eq 'ok') {
                   3608:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3609:                     }
1.637     raeburn  3610:                 }
1.1095    raeburn  3611:                 if (ref($mimetype)) {
                   3612:                     $$mimetype = $type;
                   3613:                 } 
1.637     raeburn  3614:             }
1.477     raeburn  3615:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3616:                                  $home);
1.481     raeburn  3617:             if ($fetchresult eq 'ok') {
                   3618:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3619:             } else {
                   3620:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3621:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3622:                 return '/adm/notfound.html';
                   3623:             }
1.477     raeburn  3624:         }
                   3625:     }
1.485     raeburn  3626:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3627:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3628:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3629:     }
                   3630:     return $fetchresult;
                   3631: }
                   3632: 
1.637     raeburn  3633: sub build_filepath {
                   3634:     my ($fpath) = @_;
                   3635:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3636:     unless ($fpath eq '') {
                   3637:         my @parts=split('/',$fpath);
                   3638:         foreach my $part (@parts) {
                   3639:             $filepath.= '/'.$part;
                   3640:             if ((-e $filepath)!=1) {
                   3641:                 mkdir($filepath,0777);
                   3642:             }
                   3643:         }
                   3644:     }
                   3645:     return $filepath;
                   3646: }
                   3647: 
                   3648: sub store_edited_file {
1.638     albertel 3649:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3650:     my $file = $primary_url;
                   3651:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3652:     my $fpath = '';
                   3653:     my $fname = $file;
                   3654:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3655:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3656:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3657:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3658:     print $fh $content;
                   3659:     close($fh);
1.638     albertel 3660:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3661:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3662: 			  $home);
1.637     raeburn  3663:     if ($$fetchresult eq 'ok') {
                   3664:         return '/uploaded/'.$fpath.'/'.$fname;
                   3665:     } else {
1.638     albertel 3666:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3667: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3668:         return '/adm/notfound.html';
                   3669:     }
                   3670: }
                   3671: 
1.531     albertel 3672: sub clean_filename {
1.831     albertel 3673:     my ($fname,$args)=@_;
1.315     www      3674: # Replace Windows backslashes by forward slashes
1.257     www      3675:     $fname=~s/\\/\//g;
1.831     albertel 3676:     if (!$args->{'keep_path'}) {
                   3677:         # Get rid of everything but the actual filename
                   3678: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3679:     }
1.315     www      3680: # Replace spaces by underscores
                   3681:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3682: # Transliterate non-ascii text to ascii
                   3683:     my $lang = &Apache::lonlocal::current_language();
                   3684:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3685: # Replace all other weird characters by nothing
1.831     albertel 3686:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3687: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3688: # numbers
                   3689:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3690:     return $fname;
                   3691: }
1.1172.2.110  raeburn  3692: 
1.1051    raeburn  3693: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3694: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3695: # image with the same aspect ratio as the original, but with dimensions which do 
                   3696: # not exceed $resizewidth and $resizeheight.
                   3697:  
1.984     neumanie 3698: sub resizeImage {
1.1051    raeburn  3699:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3700:     my $ima = Image::Magick->new;
                   3701:     my $resized;
                   3702:     if (-e $img_path) {
                   3703:         $ima->Read($img_path);
                   3704:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3705:             my $width = $ima->Get('width');
                   3706:             my $height = $ima->Get('height');
                   3707:             if ($width > $resizewidth) {
                   3708: 	        my $factor = $width/$resizewidth;
                   3709:                 my $newheight = $height/$factor;
                   3710:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3711:                 $resized = 1;
                   3712:             }
                   3713:         }
                   3714:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3715:             my $width = $ima->Get('width');
                   3716:             my $height = $ima->Get('height');
                   3717:             if ($height > $resizeheight) {
                   3718:                 my $factor = $height/$resizeheight;
                   3719:                 my $newwidth = $width/$factor;
                   3720:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3721:                 $resized = 1;
                   3722:             }
                   3723:         }
                   3724:         if ($resized) {
                   3725:             $ima->Write($img_path);
                   3726:         }
                   3727:     }
                   3728:     return;
1.977     amueller 3729: }
                   3730: 
1.608     albertel 3731: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3732: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3733: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3734: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3735: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3736: #                   if 'coursedoc': upload to the current course
                   3737: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3738: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3739: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3740: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3741: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3742: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3743: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3744: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3745: #        $allfiles - reference to hash for embedded objects
                   3746: #        $codebase - reference to hash for codebase of java objects
                   3747: #        $desuname - username for permanent storage of uploaded file
                   3748: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3749: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3750: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3751: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3752: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3753: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3754: #                    from File::MMagic.
1.858     raeburn  3755: # 
1.686     albertel 3756: # output: url of file in userspace, or error: <message> 
                   3757: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3758: 
1.531     albertel 3759: sub userfileupload {
1.1090    raeburn  3760:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3761:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3762:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3763:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3764:     $fname=&clean_filename($fname);
1.1090    raeburn  3765:     # See if there is anything left
1.257     www      3766:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3767:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3768:     if ($fname =~ /^\./) {
                   3769:         my ($s,$usec) = &gettimeofday();
                   3770:         while (length($usec) < 6) {
                   3771:             $usec = '0'.$usec;
                   3772:         }
                   3773:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3774:     }
1.1090    raeburn  3775:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3776:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3777:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3778:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3779:         my $now = time;
1.1090    raeburn  3780:         my $filepath;
1.1095    raeburn  3781:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3782:              $filepath = 'tmp/helprequests/'.$now;
                   3783:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3784:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3785:                          '_'.$env{'user.domain'}.'/pending';
                   3786:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3787:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3788:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3789:                 $docudom = $destudom;
                   3790:             } else {
                   3791:                 $docudom = $env{'user.domain'};
                   3792:             }
1.1172.2.96  raeburn  3793:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3794:                 $docuname = $destuname;
                   3795:             } else {
                   3796:                 $docuname = $env{'user.name'};
                   3797:             }
                   3798:             if (exists($env{'form.group'})) {
                   3799:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3800:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3801:             }
                   3802:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3803:             if ($context eq 'canceloverwrite') {
                   3804:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3805:                 if (-e  $tempfile) {
                   3806:                     my @info = stat($tempfile);
                   3807:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3808:                         unlink($tempfile);
                   3809:                     }
                   3810:                 }
                   3811:                 return;
1.523     raeburn  3812:             }
                   3813:         }
1.1090    raeburn  3814:         # Create the directory if not present
1.741     raeburn  3815:         my @parts=split(/\//,$filepath);
                   3816:         my $fullpath = $perlvar{'lonDaemons'};
                   3817:         for (my $i=0;$i<@parts;$i++) {
                   3818:             $fullpath .= '/'.$parts[$i];
                   3819:             if ((-e $fullpath)!=1) {
                   3820:                 mkdir($fullpath,0777);
                   3821:             }
                   3822:         }
1.1172.2.96  raeburn  3823:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3824:         print $fh $env{'form.'.$formname};
                   3825:         close($fh);
1.1090    raeburn  3826:         if ($context eq 'existingfile') {
                   3827:             my @info = stat($fullpath.'/'.$fname);
                   3828:             return ($fullpath.'/'.$fname,$info[9]);
                   3829:         } else {
                   3830:             return $fullpath.'/'.$fname;
                   3831:         }
1.523     raeburn  3832:     }
1.995     raeburn  3833:     if ($subdir eq 'scantron') {
                   3834:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3835:     } else {
1.995     raeburn  3836:         $fname="$subdir/$fname";
                   3837:     }
1.1090    raeburn  3838:     if ($context eq 'coursedoc') {
1.638     albertel 3839: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3840: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3841:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3842:             return &finishuserfileupload($docuname,$docudom,
                   3843: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3844: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3845:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3846:         } else {
1.1172.2.21  raeburn  3847:             if ($env{'form.folder'}) {
                   3848:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3849:             }
1.638     albertel 3850:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3851: 				       $fname,$formname,$parser,
1.1095    raeburn  3852: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3853:         }
1.719     banghart 3854:     } elsif (defined($destuname)) {
                   3855:         my $docuname=$destuname;
                   3856:         my $docudom=$destudom;
1.860     raeburn  3857: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3858: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3859:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3860:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3861:     } else {
1.638     albertel 3862:         my $docuname=$env{'user.name'};
                   3863:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3864:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3865:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3866:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3867:         }
1.860     raeburn  3868: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3869: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3870:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3871:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3872:     }
1.271     www      3873: }
                   3874: 
                   3875: sub finishuserfileupload {
1.860     raeburn  3876:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3877:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3878:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3879:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3880:   
1.860     raeburn  3881:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3882:     $file=$fname;
                   3883:     if ($fname=~m|/|) {
                   3884:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3885: 	$path.=$fnamepath.'/';
                   3886:     }
1.259     www      3887:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3888:     my $count;
                   3889:     for ($count=4;$count<=$#parts;$count++) {
                   3890:         $filepath.="/$parts[$count]";
                   3891:         if ((-e $filepath)!=1) {
                   3892: 	    mkdir($filepath,0777);
                   3893:         }
                   3894:     }
1.984     neumanie 3895: 
1.258     www      3896: # Save the file
                   3897:     {
1.1172.2.96  raeburn  3898: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3899: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3900: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3901: 	    return '/adm/notfound.html';
                   3902: 	}
1.1090    raeburn  3903:         if ($context eq 'overwrite') {
1.1117    foxr     3904:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3905:             my $target = $filepath.'/'.$file;
                   3906:             if (-e $source) {
                   3907:                 my @info = stat($source);
                   3908:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3909:                     unless (&File::Copy::move($source,$target)) {
                   3910:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3911:                         return "Moving from $source failed";
                   3912:                     }
                   3913:                 } else {
                   3914:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3915:                 }
                   3916:             } else {
                   3917:                 return "Temporary file: $source missing";
                   3918:             }
                   3919:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3920: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3921: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3922: 	    return '/adm/notfound.html';
                   3923: 	}
1.570     albertel 3924: 	close(FH);
1.1051    raeburn  3925:         if ($resizewidth && $resizeheight) {
                   3926:             my $mm = new File::MMagic;
                   3927:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3928:             if ($mime_type =~ m{^image/}) {
                   3929: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3930:             }  
1.977     amueller 3931: 	}
1.258     www      3932:     }
1.1152    raeburn  3933:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3934:         if (ref($mimetype)) {
                   3935:             if ($$mimetype eq '') {
                   3936:                 my $mm = new File::MMagic;
                   3937:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3938:                 $$mimetype = $type;
                   3939:             }
                   3940:         }
                   3941:     }
1.1172.2.109  raeburn  3942:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3943:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3944:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3945:                                                        $allfiles,$codebase);
                   3946:             unless ($parse_result eq 'ok') {
                   3947:                 &logthis('Failed to parse '.$filepath.$file.
                   3948: 	   	         ' for embedded media: '.$parse_result); 
                   3949:             }
1.637     raeburn  3950:         }
1.1172.2.109  raeburn  3951:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3952:         my $format = $env{'form.scantron_format'};
                   3953:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3954:     }
1.860     raeburn  3955:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3956:         my $input = $filepath.'/'.$file;
                   3957:         my $output = $filepath.'/'.'tn-'.$file;
                   3958:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3959:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3960:         system({$args[0]} @args);
1.860     raeburn  3961:         if (-e $filepath.'/'.'tn-'.$file) {
                   3962:             $fetchthumb  = 1; 
                   3963:         }
                   3964:     }
1.858     raeburn  3965:  
1.259     www      3966: # Notify homeserver to grep it
                   3967: #
1.984     neumanie 3968:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3969:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3970:     if ($fetchresult eq 'ok') {
1.860     raeburn  3971:         if ($fetchthumb) {
                   3972:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3973:             if ($thumbresult ne 'ok') {
                   3974:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3975:                          $docuhome.': '.$thumbresult);
                   3976:             }
                   3977:         }
1.259     www      3978: #
1.258     www      3979: # Return the URL to it
1.494     albertel 3980:         return '/uploaded/'.$path.$file;
1.263     www      3981:     } else {
1.494     albertel 3982:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3983: 		 ': '.$fetchresult);
1.263     www      3984:         return '/adm/notfound.html';
1.858     raeburn  3985:     }
1.493     albertel 3986: }
                   3987: 
1.637     raeburn  3988: sub extract_embedded_items {
1.961     raeburn  3989:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3990:     my @state = ();
1.1164    raeburn  3991:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3992:     my %javafiles = (
                   3993:                       codebase => '',
                   3994:                       code => '',
                   3995:                       archive => ''
                   3996:                     );
                   3997:     my %mediafiles = (
                   3998:                       src => '',
                   3999:                       movie => '',
                   4000:                      );
1.648     raeburn  4001:     my $p;
                   4002:     if ($content) {
                   4003:         $p = HTML::LCParser->new($content);
                   4004:     } else {
1.961     raeburn  4005:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4006:     }
1.641     albertel 4007:     while (my $t=$p->get_token()) {
1.640     albertel 4008: 	if ($t->[0] eq 'S') {
                   4009: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4010: 	    push(@state, $tagname);
1.648     raeburn  4011:             if (lc($tagname) eq 'allow') {
                   4012:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4013:             }
1.640     albertel 4014: 	    if (lc($tagname) eq 'img') {
                   4015: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4016: 	    }
1.886     albertel 4017: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4018:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4019: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4020:                 }
1.886     albertel 4021: 	    }
1.645     raeburn  4022:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4023:                 my $src;
1.645     raeburn  4024:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4025:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4026:                 } else {
1.1164    raeburn  4027:                     if ($attr->{'src'} ne '') {
                   4028:                         $src = $attr->{'src'};
                   4029:                         &add_filetype($allfiles,$src,'src');
                   4030:                     }
                   4031:                 }
                   4032:                 my $text = $p->get_trimmed_text();
                   4033:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4034:                     my @swfargs = split(/,/,$1);
                   4035:                     foreach my $item (@swfargs) {
                   4036:                         $item =~ s/["']//g;
                   4037:                         $item =~ s/^\s+//;
                   4038:                         $item =~ s/\s+$//;
                   4039:                     }
                   4040:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4041:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4042:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4043:                         } else {
                   4044:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4045:                         }
                   4046:                     }
1.645     raeburn  4047:                 }
                   4048:             }
                   4049:             if (lc($tagname) eq 'link') {
                   4050:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4051:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4052:                 }
                   4053:             }
1.640     albertel 4054: 	    if (lc($tagname) eq 'object' ||
                   4055: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4056: 		foreach my $item (keys(%javafiles)) {
                   4057: 		    $javafiles{$item} = '';
                   4058: 		}
1.1164    raeburn  4059:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4060:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4061:                 }
1.640     albertel 4062: 	    }
                   4063: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4064: 		my $name = lc($attr->{'name'});
                   4065: 		foreach my $item (keys(%javafiles)) {
                   4066: 		    if ($name eq $item) {
                   4067: 			$javafiles{$item} = $attr->{'value'};
                   4068: 			last;
                   4069: 		    }
                   4070: 		}
1.1164    raeburn  4071:                 my $pathfrom;
1.640     albertel 4072: 		foreach my $item (keys(%mediafiles)) {
                   4073: 		    if ($name eq $item) {
1.1164    raeburn  4074:                         $pathfrom = $attr->{'value'};
                   4075:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4076: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4077: 			last;
                   4078: 		    }
                   4079: 		}
1.1164    raeburn  4080:                 if ($name eq 'flashvars') {
                   4081:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4082:                 }
                   4083:                 if ($pathfrom ne '') {
                   4084:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4085:                                          $pathfrom);
                   4086:                 }
1.640     albertel 4087: 	    }
                   4088: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4089: 		foreach my $item (keys(%javafiles)) {
                   4090: 		    if ($attr->{$item}) {
                   4091: 			$javafiles{$item} = $attr->{$item};
                   4092: 			last;
                   4093: 		    }
                   4094: 		}
                   4095: 		foreach my $item (keys(%mediafiles)) {
                   4096: 		    if ($attr->{$item}) {
                   4097: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4098: 			last;
                   4099: 		    }
                   4100: 		}
1.1164    raeburn  4101:                 if (lc($tagname) eq 'embed') {
                   4102:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4103:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4104:                                              $attr->{'src'});
                   4105:                     }
                   4106:                 }
1.640     albertel 4107: 	    }
1.1172.2.35  raeburn  4108:             if (lc($tagname) eq 'iframe') {
                   4109:                 my $src = $attr->{'src'} ;
                   4110:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4111:                     &add_filetype($allfiles,$src,'src');
                   4112:                 } elsif ($src =~ m{^/}) {
                   4113:                     if ($env{'request.course.id'}) {
                   4114:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4115:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4116:                         my $url = &hreflocation('',$fullpath);
                   4117:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4118:                             my $relpath = $1;
                   4119:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4120:                                 &add_filetype($allfiles,$1,'src');
                   4121:                             }
                   4122:                         }
                   4123:                     }
                   4124:                 }
                   4125:             }
1.1164    raeburn  4126:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4127:                 pop(@state);
1.1164    raeburn  4128:             }
1.640     albertel 4129: 	} elsif ($t->[0] eq 'E') {
                   4130: 	    my ($tagname) = ($t->[1]);
                   4131: 	    if ($javafiles{'codebase'} ne '') {
                   4132: 		$javafiles{'codebase'} .= '/';
                   4133: 	    }  
                   4134: 	    if (lc($tagname) eq 'applet' ||
                   4135: 		lc($tagname) eq 'object' ||
                   4136: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4137: 		) {
                   4138: 		foreach my $item (keys(%javafiles)) {
                   4139: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4140: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4141: 			&add_filetype($allfiles,$file,$item);
                   4142: 		    }
                   4143: 		}
                   4144: 	    } 
                   4145: 	    pop @state;
                   4146: 	}
                   4147:     }
1.1164    raeburn  4148:     foreach my $id (sort(keys(%flashvars))) {
                   4149:         if ($shockwave{$id} ne '') {
                   4150:             my @pairs = split(/\&/,$flashvars{$id});
                   4151:             foreach my $pair (@pairs) {
                   4152:                 my ($key,$value) = split(/\=/,$pair);
                   4153:                 if ($key eq 'thumb') {
                   4154:                     &add_filetype($allfiles,$value,$key);
                   4155:                 } elsif ($key eq 'content') {
                   4156:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4157:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4158:                     if ($ext ne '') {
                   4159:                         &add_filetype($allfiles,$path.$value,$ext);
                   4160:                     }
                   4161:                 }
                   4162:             }
                   4163:         }
                   4164:     }
1.637     raeburn  4165:     return 'ok';
                   4166: }
                   4167: 
1.639     albertel 4168: sub add_filetype {
                   4169:     my ($allfiles,$file,$type)=@_;
                   4170:     if (exists($allfiles->{$file})) {
                   4171: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4172: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4173: 	}
                   4174:     } else {
                   4175: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4176:     }
                   4177: }
                   4178: 
1.1164    raeburn  4179: sub embedded_dependency {
                   4180:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4181:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4182:         if (($identifier ne '') &&
                   4183:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4184:             ($pathfrom ne '')) {
                   4185:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4186:             foreach my $dep (@{$related->{$identifier}}) {
                   4187:                 &add_filetype($allfiles,$path.$dep,'object');
                   4188:             }
                   4189:         }
                   4190:     }
                   4191:     return;
                   4192: }
                   4193: 
1.1172.2.109  raeburn  4194: sub bubblesheet_converter {
                   4195:     my ($cdom,$fullpath,$config,$format) = @_;
                   4196:     if ((&domain($cdom) ne '') &&
                   4197:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4198:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4199:         my (%csvcols,%csvoptions);
                   4200:         if (ref($config->{'fields'}) eq 'HASH') {
                   4201:             %csvcols = %{$config->{'fields'}};
                   4202:         }
                   4203:         if (ref($config->{'options'}) eq 'HASH') {
                   4204:             %csvoptions = %{$config->{'options'}};
                   4205:         }
                   4206:         my %csvbynum = reverse(%csvcols);
                   4207:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4208:         if (keys(%scantronconf)) {
                   4209:             my %bynum = (
                   4210:                           $scantronconf{CODEstart} => 'CODEstart',
                   4211:                           $scantronconf{IDstart}   => 'IDstart',
                   4212:                           $scantronconf{PaperID}   => 'PaperID',
                   4213:                           $scantronconf{FirstName} => 'FirstName',
                   4214:                           $scantronconf{LastName}  => 'LastName',
                   4215:                           $scantronconf{Qstart}    => 'Qstart',
                   4216:                         );
                   4217:             my @ordered;
                   4218:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4219:                 push(@ordered,$bynum{$item});
                   4220:             }
                   4221:             my %mapstart = (
                   4222:                               CODEstart => 'CODE',
                   4223:                               IDstart   => 'ID',
                   4224:                               PaperID   => 'PaperID',
                   4225:                               FirstName => 'FirstName',
                   4226:                               LastName  => 'LastName',
                   4227:                               Qstart    => 'FirstQuestion',
                   4228:                            );
                   4229:             my %maplength = (
                   4230:                               CODEstart => 'CODElength',
                   4231:                               IDstart   => 'IDlength',
                   4232:                               PaperID   => 'PaperIDlength',
                   4233:                               FirstName => 'FirstNamelength',
                   4234:                               LastName  => 'LastNamelength',
                   4235:             );
                   4236:             if (open(my $fh,'<',$fullpath)) {
                   4237:                 my $output;
                   4238:                 my %lettdig = &letter_to_digits();
                   4239:                 my %diglett = reverse(%lettdig);
                   4240:                 my $numletts = scalar(keys(%lettdig));
                   4241:                 my $num = 0;
                   4242:                 while (my $line=<$fh>) {
                   4243:                     $num ++;
                   4244:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4245:                     $line =~ s{[\r\n]+$}{};
                   4246:                     my %found;
                   4247:                     my @values = split(/,/,$line);
                   4248:                     my ($qstart,$record);
                   4249:                     for (my $i=0; $i<@values; $i++) {
                   4250:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4251:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4252:                             if ($values[$i] eq '') {
                   4253:                                 $values[$i] = $scantronconf{'Qoff'};
                   4254:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4255:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4256:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4257:                                 }
                   4258:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4259:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4260:                                     $values[$i] = $diglett{$values[$i]};
                   4261:                                 }
                   4262:                             } else {
                   4263:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4264:                                     my $digit;
                   4265:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4266:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4267:                                         if ($values[$i] eq 'J') {
                   4268:                                             $digit += $numletts;
                   4269:                                         }
                   4270:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4271:                                         $digit = $values[$i]-1;
                   4272:                                         if ($values[$i] eq '0') {
                   4273:                                             $digit += $numletts;
                   4274:                                         }
                   4275:                                     }
                   4276:                                     my $qval='';
                   4277:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4278:                                         if ($j == $digit) {
                   4279:                                             $qval .= $scantronconf{'Qon'};
                   4280:                                         } else {
                   4281:                                             $qval .= $scantronconf{'Qoff'};
                   4282:                                         }
                   4283:                                     }
                   4284:                                     $values[$i] = $qval;
                   4285:                                 }
                   4286:                             }
                   4287:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4288:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4289:                             }
                   4290:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4291:                             if ($numblank > 0) {
                   4292:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4293:                             }
                   4294:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4295:                                 $qstart = $i;
                   4296:                                 $found{$csvbynum{$i}} = $values[$i];
                   4297:                             } else {
                   4298:                                 $found{'FirstQuestion'} .= $values[$i];
                   4299:                             }
                   4300:                         } elsif (exists($csvbynum{$i})) {
                   4301:                             if ($csvoptions{'rem'}) {
                   4302:                                 $values[$i] =~ s/^\s+//;
                   4303:                             }
                   4304:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4305:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4306:                                     $values[$i] = '0'.$values[$i];
                   4307:                                 }
                   4308:                             }
                   4309:                             $found{$csvbynum{$i}} = $values[$i];
                   4310:                         }
                   4311:                     }
                   4312:                     foreach my $item (@ordered) {
                   4313:                         my $currlength = 1+length($record);
                   4314:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4315:                         if ($numspaces > 0) {
                   4316:                             $record .= (' ' x $numspaces);
                   4317:                         }
                   4318:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4319:                             unless ($item eq 'Qstart') {
                   4320:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4321:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4322:                                 }
                   4323:                             }
                   4324:                             $record .= $found{$mapstart{$item}};
                   4325:                         }
                   4326:                     }
                   4327:                     $output .= "$record\n";
                   4328:                 }
                   4329:                 close($fh);
                   4330:                 if ($output) {
                   4331:                     if (open(my $fh,'>',$fullpath)) {
                   4332:                         print $fh $output;
                   4333:                         close($fh);
                   4334:                     }
                   4335:                 }
                   4336:             }
                   4337:         }
                   4338:         return;
                   4339:     }
                   4340: }
                   4341: 
                   4342: sub letter_to_digits {
                   4343:     my %lettdig = (
                   4344:                     A => 1,
                   4345:                     B => 2,
                   4346:                     C => 3,
                   4347:                     D => 4,
                   4348:                     E => 5,
                   4349:                     F => 6,
                   4350:                     G => 7,
                   4351:                     H => 8,
                   4352:                     I => 9,
                   4353:                     J => 0,
                   4354:                   );
                   4355:     return %lettdig;
                   4356: }
                   4357: 
                   4358: sub get_scantron_config {
                   4359:     my ($which,$cdom) = @_;
                   4360:     my @lines = &get_scantronformat_file($cdom);
                   4361:     my %config;
                   4362:     #FIXME probably should move to XML it has already gotten a bit much now
                   4363:     foreach my $line (@lines) {
                   4364:         my ($name,$descrip)=split(/:/,$line);
                   4365:         if ($name ne $which ) { next; }
                   4366:         chomp($line);
                   4367:         my @config=split(/:/,$line);
                   4368:         $config{'name'}=$config[0];
                   4369:         $config{'description'}=$config[1];
                   4370:         $config{'CODElocation'}=$config[2];
                   4371:         $config{'CODEstart'}=$config[3];
                   4372:         $config{'CODElength'}=$config[4];
                   4373:         $config{'IDstart'}=$config[5];
                   4374:         $config{'IDlength'}=$config[6];
                   4375:         $config{'Qstart'}=$config[7];
                   4376:         $config{'Qlength'}=$config[8];
                   4377:         $config{'Qoff'}=$config[9];
                   4378:         $config{'Qon'}=$config[10];
                   4379:         $config{'PaperID'}=$config[11];
                   4380:         $config{'PaperIDlength'}=$config[12];
                   4381:         $config{'FirstName'}=$config[13];
                   4382:         $config{'FirstNamelength'}=$config[14];
                   4383:         $config{'LastName'}=$config[15];
                   4384:         $config{'LastNamelength'}=$config[16];
                   4385:         $config{'BubblesPerRow'}=$config[17];
                   4386:         last;
                   4387:     }
                   4388:     return %config;
                   4389: }
                   4390: 
                   4391: sub get_scantronformat_file {
                   4392:     my ($cdom) = @_;
                   4393:     if ($cdom eq '') {
                   4394:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4395:     }
                   4396:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4397:     my $gottab = 0;
                   4398:     my @lines;
                   4399:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4400:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4401:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4402:             if ($formatfile ne '-1') {
                   4403:                 @lines = split("\n",$formatfile,-1);
                   4404:                 $gottab = 1;
                   4405:             }
                   4406:         }
                   4407:     }
                   4408:     if (!$gottab) {
                   4409:         my $confname = $cdom.'-domainconfig';
                   4410:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4411:         my $formatfile = &getfile($default);
                   4412:         if ($formatfile ne '-1') {
                   4413:             @lines = split("\n",$formatfile,-1);
                   4414:             $gottab = 1;
                   4415:         }
                   4416:     }
                   4417:     if (!$gottab) {
                   4418:         my @domains = &current_machine_domains();
                   4419:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4420:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4421:                 @lines = <$fh>;
                   4422:                 close($fh);
                   4423:             }
                   4424:         } else {
                   4425:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4426:                 @lines = <$fh>;
                   4427:                 close($fh);
                   4428:             }
                   4429:         }
                   4430:     }
                   4431:     return @lines;
                   4432: }
                   4433: 
1.493     albertel 4434: sub removeuploadedurl {
1.984     neumanie 4435:     my ($url)=@_;	
                   4436:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4437:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4438: }
                   4439: 
                   4440: sub removeuserfile {
                   4441:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4442:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4443:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4444:     if ($result eq 'ok') {	
1.798     raeburn  4445:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4446:             my $metafile = $fname.'.meta';
                   4447:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4448: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4449:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4450:             my $sqlresult = 
1.823     albertel 4451:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4452:                                         'portfolio_metadata',$group,
                   4453:                                         'delete');
1.798     raeburn  4454:         }
                   4455:     }
                   4456:     return $result;
1.257     www      4457: }
1.15      www      4458: 
1.530     albertel 4459: sub mkdiruserfile {
                   4460:     my ($docuname,$docudom,$dir)=@_;
                   4461:     my $home=&homeserver($docuname,$docudom);
                   4462:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4463: }
                   4464: 
1.531     albertel 4465: sub renameuserfile {
                   4466:     my ($docuname,$docudom,$old,$new)=@_;
                   4467:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4468:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4469:                         &escape("$old").':'.&escape("$new"),$home);
                   4470:     if ($result eq 'ok') {
                   4471:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4472:             my $oldmeta = $old.'.meta';
                   4473:             my $newmeta = $new.'.meta';
                   4474:             my $metaresult = 
                   4475:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4476: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4477:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4478:             my $sqlresult = 
1.823     albertel 4479:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4480:                                         'portfolio_metadata',$group,
                   4481:                                         'delete');
1.798     raeburn  4482:         }
                   4483:     }
                   4484:     return $result;
1.531     albertel 4485: }
                   4486: 
1.14      www      4487: # ------------------------------------------------------------------------- Log
                   4488: 
                   4489: sub log {
                   4490:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4491:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4492: }
                   4493: 
                   4494: # ------------------------------------------------------------------ Course Log
1.352     www      4495: #
                   4496: # This routine flushes several buffers of non-mission-critical nature
                   4497: #
1.157     www      4498: 
                   4499: sub flushcourselogs {
1.352     www      4500:     &logthis('Flushing log buffers');
                   4501: #
                   4502: # course logs
                   4503: # This is a log of all transactions in a course, which can be used
                   4504: # for data mining purposes
                   4505: #
                   4506: # It also collects the courseid database, which lists last transaction
                   4507: # times and course titles for all courseids
                   4508: #
                   4509:     my %courseidbuffer=();
1.921     raeburn  4510:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4511:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4512: 		          &escape($courselogs{$crsid}),
                   4513: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4514: 	    delete $courselogs{$crsid};
                   4515:         } else {
                   4516:             &logthis('Failed to flush log buffer for '.$crsid);
                   4517:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4518:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4519:                         " exceeded maximum size, deleting.</font>");
                   4520:                delete $courselogs{$crsid};
                   4521:             }
1.352     www      4522:         }
1.920     raeburn  4523:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4524:             'description' => $coursedescrbuf{$crsid},
                   4525:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4526:             'type'        => $coursetypebuf{$crsid},
                   4527:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4528:         };
1.191     harris41 4529:     }
1.352     www      4530: #
                   4531: # Write course id database (reverse lookup) to homeserver of courses 
                   4532: # Is used in pickcourse
                   4533: #
1.840     albertel 4534:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4535:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4536:                                     $courseidbuffer{$crs_home},
                   4537:                                     $crs_home,'timeonly');
1.352     www      4538:     }
                   4539: #
                   4540: # File accesses
                   4541: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4542: #
1.449     matthew  4543:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4544:         if ($entry =~ /___count$/) {
                   4545:             my ($dom,$name);
1.807     albertel 4546:             ($dom,$name,undef)=
1.811     albertel 4547: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4548:             if (! defined($dom) || $dom eq '' || 
                   4549:                 ! defined($name) || $name eq '') {
1.620     albertel 4550:                 my $cid = $env{'request.course.id'};
                   4551:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4552:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4553:             }
1.450     matthew  4554:             my $value = $accesshash{$entry};
                   4555:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4556:             my %temphash=($url => $value);
1.449     matthew  4557:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4558:             if ($result eq 'ok') {
                   4559:                 delete $accesshash{$entry};
                   4560:             }
                   4561:         } else {
1.811     albertel 4562:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4563:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4564:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4565:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4566:                 delete $accesshash{$entry};
                   4567:             }
1.185     www      4568:         }
1.191     harris41 4569:     }
1.352     www      4570: #
                   4571: # Roles
                   4572: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4573: #
1.800     albertel 4574:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4575:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4576: 	    split(/\:/,$entry);
                   4577:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4578:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4579:                 $rudom,$runame) eq 'ok') {
                   4580: 	    delete $userrolehash{$entry};
                   4581:         }
                   4582:     }
1.662     raeburn  4583: #
1.1172.2.90  raeburn  4584: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4585: #
                   4586:     my %domrolebuffer = ();
1.1000    raeburn  4587:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4588:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4589:         if ($domrolebuffer{$rudom}) {
                   4590:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4591:                       '='.&escape($domainrolehash{$entry});
                   4592:         } else {
                   4593:             $domrolebuffer{$rudom}.=&escape($entry).
                   4594:                       '='.&escape($domainrolehash{$entry});
                   4595:         }
                   4596:         delete $domainrolehash{$entry};
                   4597:     }
                   4598:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4599:         my %servers;
                   4600:         if (defined(&domain($dom,'primary'))) {
                   4601:             my $primary=&domain($dom,'primary');
                   4602:             my $hostname=&hostname($primary);
                   4603:             $servers{$primary} = $hostname;
                   4604:         } else {
                   4605:             %servers = &get_servers($dom,'library');
                   4606:         }
1.841     albertel 4607: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4608: 	    if (&reply('domroleput:'.$dom.':'.
                   4609: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4610: 	        last;
                   4611: 	    } else {
1.841     albertel 4612: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4613: 	    }
1.662     raeburn  4614:         }
                   4615:     }
1.186     www      4616:     $dumpcount++;
1.157     www      4617: }
                   4618: 
                   4619: sub courselog {
                   4620:     my $what=shift;
1.158     www      4621:     $what=time.':'.$what;
1.620     albertel 4622:     unless ($env{'request.course.id'}) { return ''; }
                   4623:     $coursedombuf{$env{'request.course.id'}}=
                   4624:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4625:     $coursenumbuf{$env{'request.course.id'}}=
                   4626:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4627:     $coursehombuf{$env{'request.course.id'}}=
                   4628:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4629:     $coursedescrbuf{$env{'request.course.id'}}=
                   4630:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4631:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4632:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4633:     $courseownerbuf{$env{'request.course.id'}}=
                   4634:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4635:     $coursetypebuf{$env{'request.course.id'}}=
                   4636:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4637:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4638: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4639:     } else {
1.620     albertel 4640: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4641:     }
1.620     albertel 4642:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4643: 	&flushcourselogs();
                   4644:     }
1.158     www      4645: }
                   4646: 
                   4647: sub courseacclog {
                   4648:     my $fnsymb=shift;
1.620     albertel 4649:     unless ($env{'request.course.id'}) { return ''; }
                   4650:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4651:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4652:         $what.=':POST';
1.583     matthew  4653:         # FIXME: Probably ought to escape things....
1.800     albertel 4654: 	foreach my $key (keys(%env)) {
                   4655:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4656:                 my $formitem = $1;
                   4657:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4658:                     $what.=':'.$formitem.'='.$env{$key};
                   4659:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4660:                     $what.=':'.$formitem.'='.$env{$key};
                   4661:                 }
1.158     www      4662:             }
1.191     harris41 4663:         }
1.583     matthew  4664:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4665:         # FIXME: We should not be depending on a form parameter that someone
                   4666:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4667:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4668:             $what.= ':POST';
                   4669:             # FIXME: Probably ought to escape things....
                   4670:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4671:                                  'crsdiscuss') {
1.620     albertel 4672:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4673:             }
                   4674:         }
1.158     www      4675:     }
                   4676:     &courselog($what);
1.149     www      4677: }
                   4678: 
1.185     www      4679: sub countacc {
                   4680:     my $url=&declutter(shift);
1.458     matthew  4681:     return if (! defined($url) || $url eq '');
1.620     albertel 4682:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4683: #
                   4684: # Mark that this url was used in this course
                   4685: #
1.620     albertel 4686:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4687: #
                   4688: # Increase the access count for this resource in this child process
                   4689: #
1.281     www      4690:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4691:     $accesshash{$key}++;
1.185     www      4692: }
1.349     www      4693: 
1.361     www      4694: sub linklog {
                   4695:     my ($from,$to)=@_;
                   4696:     $from=&declutter($from);
                   4697:     $to=&declutter($to);
                   4698:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4699:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4700: }
1.1160    www      4701: 
                   4702: sub statslog {
                   4703:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4704:     if ($users<2) { return; }
                   4705:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4706:             'course'       => $env{'request.course.id'},
                   4707:             'sections'     => '"all"',
                   4708:             'num_students' => $users,
                   4709:             'part'         => $part,
                   4710:             'symb'         => $symb,
                   4711:             'mean_tries'   => $av_attempts,
                   4712:             'deg_of_diff'  => $degdiff});
                   4713:     foreach my $key (keys(%dynstore)) {
                   4714:         $accesshash{$key}=$dynstore{$key};
                   4715:     }
                   4716: }
1.361     www      4717:   
1.349     www      4718: sub userrolelog {
                   4719:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4720:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4721:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4722:        $userrolehash
                   4723:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4724:                     =$tend.':'.$tstart;
1.662     raeburn  4725:     }
1.1169    droeschl 4726:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4727:        $userrolehash
                   4728:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4729:                     =$tend.':'.$tstart;
                   4730:     }
1.1172.2.90  raeburn  4731:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4732:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4733:        $domainrolehash
                   4734:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4735:                     = $tend.':'.$tstart;
                   4736:     }
1.351     www      4737: }
                   4738: 
1.957     raeburn  4739: sub courserolelog {
                   4740:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4741:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4742:         my $cdom = $1;
                   4743:         my $cnum = $2;
                   4744:         my $sec = $3;
                   4745:         my $namespace = 'rolelog';
                   4746:         my %storehash = (
                   4747:                            role    => $trole,
                   4748:                            start   => $tstart,
                   4749:                            end     => $tend,
                   4750:                            selfenroll => $selfenroll,
                   4751:                            context    => $context,
                   4752:                         );
                   4753:         if ($trole eq 'gr') {
                   4754:             $namespace = 'groupslog';
                   4755:             $storehash{'group'} = $sec;
                   4756:         } else {
                   4757:             $storehash{'section'} = $sec;
                   4758:         }
                   4759:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4760:                    $domain,$cnum,$cdom);
                   4761:         if (($trole ne 'st') || ($sec ne '')) {
                   4762:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4763:         }
                   4764:     }
                   4765:     return;
                   4766: }
                   4767: 
1.1172.2.9  raeburn  4768: sub domainrolelog {
                   4769:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4770:     if ($area =~ m{^/($match_domain)/$}) {
                   4771:         my $cdom = $1;
                   4772:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4773:         my $namespace = 'rolelog';
                   4774:         my %storehash = (
                   4775:                            role    => $trole,
                   4776:                            start   => $tstart,
                   4777:                            end     => $tend,
                   4778:                            context => $context,
                   4779:                         );
                   4780:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4781:                    $domain,$domconfiguser,$cdom);
                   4782:     }
                   4783:     return;
                   4784: 
                   4785: }
                   4786: 
                   4787: sub coauthorrolelog {
                   4788:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4789:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4790:         my $audom = $1;
                   4791:         my $auname = $2;
                   4792:         my $namespace = 'rolelog';
                   4793:         my %storehash = (
                   4794:                            role    => $trole,
                   4795:                            start   => $tstart,
                   4796:                            end     => $tend,
                   4797:                            context => $context,
                   4798:                         );
                   4799:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4800:                    $domain,$auname,$audom);
                   4801:     }
                   4802:     return;
                   4803: }
                   4804: 
1.351     www      4805: sub get_course_adv_roles {
1.948     raeburn  4806:     my ($cid,$codes) = @_;
1.620     albertel 4807:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4808:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4809:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4810:     my %nothide=();
1.800     albertel 4811:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4812:         if ($user !~ /:/) {
                   4813: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4814:         } else {
                   4815:             $nothide{$user}=1;
                   4816:         }
1.470     www      4817:     }
1.1172.2.23  raeburn  4818:     my @possdoms = ($coursehash{'domain'});
                   4819:     if ($coursehash{'checkforpriv'}) {
                   4820:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4821:     }
1.351     www      4822:     my %returnhash=();
                   4823:     my %dumphash=
                   4824:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4825:     my $now=time;
1.997     raeburn  4826:     my %privileged;
1.1000    raeburn  4827:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4828: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4829:         if (($tstart) && ($tstart<0)) { next; }
                   4830:         if (($tend) && ($tend<$now)) { next; }
                   4831:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4832:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4833: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4834:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4835:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4836: 	if ($role eq 'cr') { next; }
1.948     raeburn  4837:         if ($codes) {
                   4838:             if ($section) { $role .= ':'.$section; }
                   4839:             if ($returnhash{$role}) {
                   4840:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4841:             } else {
                   4842:                 $returnhash{$role}=$username.':'.$domain;
                   4843:             }
1.351     www      4844:         } else {
1.988     raeburn  4845:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4846:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4847:             if ($returnhash{$key}) {
                   4848: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4849:             } else {
                   4850:                 $returnhash{$key}=$username.':'.$domain;
                   4851:             }
1.351     www      4852:         }
1.948     raeburn  4853:     }
1.400     www      4854:     return %returnhash;
                   4855: }
                   4856: 
                   4857: sub get_my_roles {
1.937     raeburn  4858:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4859:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4860:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4861:     my (%dumphash,%nothide);
1.1086    raeburn  4862:     if ($context eq 'userroles') {
1.1166    raeburn  4863:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4864:     } else {
1.1172.2.23  raeburn  4865:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4866:         if ($hidepriv) {
                   4867:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4868:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4869:                 if ($user !~ /:/) {
                   4870:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4871:                 } else {
                   4872:                     $nothide{$user} = 1;
                   4873:                 }
                   4874:             }
                   4875:         }
1.858     raeburn  4876:     }
1.400     www      4877:     my %returnhash=();
                   4878:     my $now=time;
1.999     raeburn  4879:     my %privileged;
1.800     albertel 4880:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4881:         my ($role,$tend,$tstart);
                   4882:         if ($context eq 'userroles') {
1.1149    raeburn  4883:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4884: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4885:         } else {
                   4886:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4887:         }
1.400     www      4888:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4889:         my $status = 'active';
1.939     raeburn  4890:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4891:             $status = 'previous';
                   4892:         } 
                   4893:         if (($tstart) && ($now<$tstart)) {
                   4894:             $status = 'future';
                   4895:         }
                   4896:         if (ref($types) eq 'ARRAY') {
                   4897:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4898:                 next;
                   4899:             } 
                   4900:         } else {
                   4901:             if ($status ne 'active') {
                   4902:                 next;
                   4903:             }
                   4904:         }
1.867     raeburn  4905:         my ($rolecode,$username,$domain,$section,$area);
                   4906:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4907:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4908:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4909:         } else {
                   4910:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4911:         }
1.832     raeburn  4912:         if (ref($roledoms) eq 'ARRAY') {
                   4913:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4914:                 next;
                   4915:             }
                   4916:         }
                   4917:         if (ref($roles) eq 'ARRAY') {
                   4918:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4919:                 if ($role =~ /^cr\//) {
                   4920:                     if (!grep(/^cr$/,@{$roles})) {
                   4921:                         next;
                   4922:                     }
1.1104    raeburn  4923:                 } elsif ($role =~ /^gr\//) {
                   4924:                     if (!grep(/^gr$/,@{$roles})) {
                   4925:                         next;
                   4926:                     }
1.922     raeburn  4927:                 } else {
                   4928:                     next;
                   4929:                 }
1.832     raeburn  4930:             }
1.867     raeburn  4931:         }
1.937     raeburn  4932:         if ($hidepriv) {
1.1172.2.23  raeburn  4933:             my @privroles = ('dc','su');
1.999     raeburn  4934:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4935:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4936:             } else {
1.1172.2.23  raeburn  4937:                 my $possdoms = [$domain];
                   4938:                 if (ref($roledoms) eq 'ARRAY') {
                   4939:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4940:                 }
1.1172.2.23  raeburn  4941:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4942:                     if (!$nothide{$username.':'.$domain}) {
                   4943:                         next;
                   4944:                     }
                   4945:                 }
1.937     raeburn  4946:             }
                   4947:         }
1.933     raeburn  4948:         if ($withsec) {
                   4949:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4950:                 $tstart.':'.$tend;
                   4951:         } else {
                   4952:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4953:         }
1.832     raeburn  4954:     }
1.373     www      4955:     return %returnhash;
1.399     www      4956: }
                   4957: 
1.1172.2.89  raeburn  4958: sub get_all_adhocroles {
                   4959:     my ($dom) = @_;
                   4960:     my @roles_by_num = ();
                   4961:     my %domdefaults = &get_domain_defaults($dom);
                   4962:     my (%description,%access_in_dom,%access_info);
                   4963:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4964:         my $count = 0;
                   4965:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4966:         my %ordered;
                   4967:         foreach my $role (sort(keys(%domcurrent))) {
                   4968:             my ($order,$desc,$access_in_dom);
                   4969:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4970:                 $order = $domcurrent{$role}{'order'};
                   4971:                 $desc = $domcurrent{$role}{'desc'};
                   4972:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4973:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4974:             }
                   4975:             if ($order eq '') {
                   4976:                 $order = $count;
                   4977:             }
                   4978:             $ordered{$order} = $role;
                   4979:             if ($desc ne '') {
                   4980:                 $description{$role} = $desc;
                   4981:             } else {
                   4982:                 $description{$role}= $role;
                   4983:             }
                   4984:             $count++;
                   4985:         }
                   4986:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4987:             push(@roles_by_num,$ordered{$item});
                   4988:         }
                   4989:     }
                   4990:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4991: }
                   4992: 
                   4993: sub get_my_adhocroles {
                   4994:     my ($cid,$checkreg) = @_;
                   4995:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4996:     if ($env{'request.course.id'} eq $cid) {
                   4997:         $cdom = $env{'course.'.$cid.'.domain'};
                   4998:         $cnum = $env{'course.'.$cid.'.num'};
                   4999:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5000:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5001:         $cdom = $1;
                   5002:         $cnum = $2;
                   5003:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5004:                                      $cdom,$cnum);
                   5005:     }
                   5006:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5007:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5008:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5009:         if ($rosterhash{$user} ne '') {
                   5010:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5011:             return ([],{}) if ($type eq 'auto');
                   5012:         }
                   5013:     }
                   5014:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5015:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5016:             my $then=$env{'user.login.time'};
                   5017:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5018:             if (!$update) {
                   5019:                 $update = $then;
                   5020:             }
                   5021:             my @liveroles;
                   5022:             foreach my $role ('dh','da') {
                   5023:                 if ($env{"user.role.$role./$cdom/"}) {
                   5024:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5025:                     my $limit = $update;
                   5026:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5027:                         $limit = $then;
                   5028:                     }
                   5029:                     my $activerole = 1;
                   5030:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5031:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5032:                     if ($activerole) {
                   5033:                         push(@liveroles,$role);
                   5034:                     }
                   5035:                 }
                   5036:             }
                   5037:             if (@liveroles) {
1.1172.2.89  raeburn  5038:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5039:                     my ($accessref,$accessinfo,%access_in_dom);
                   5040:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5041:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5042:                         if (@{$roles_by_num}) {
                   5043:                             my %settings;
                   5044:                             if ($env{'request.course.id'} eq $cid) {
                   5045:                                 foreach my $envkey (keys(%env)) {
                   5046:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5047:                                         $settings{$1} = $env{$envkey};
                   5048:                                     }
                   5049:                                 }
                   5050:                             } else {
                   5051:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5052:                             }
                   5053:                             my %setincrs;
                   5054:                             if ($settings{'internal.adhocaccess'}) {
                   5055:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5056:                             }
                   5057:                             my @statuses;
                   5058:                             if ($env{'environment.inststatus'}) {
                   5059:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5060:                             }
                   5061:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5062:                             if (ref($accessref) eq 'HASH') {
                   5063:                                 %access_in_dom = %{$accessref};
                   5064:                             }
                   5065:                             foreach my $role (@{$roles_by_num}) {
                   5066:                                 my ($curraccess,@okstatus,@personnel);
                   5067:                                 if ($setincrs{$role}) {
                   5068:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5069:                                     if ($curraccess eq 'status') {
                   5070:                                         @okstatus = split(/\&/,$rest);
                   5071:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5072:                                         @personnel = split(/\&/,$rest);
                   5073:                                     }
                   5074:                                 } else {
                   5075:                                     $curraccess = $access_in_dom{$role};
                   5076:                                     if (ref($accessinfo) eq 'HASH') {
                   5077:                                         if ($curraccess eq 'status') {
                   5078:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5079:                                                 @okstatus = @{$accessinfo->{$role}};
                   5080:                                             }
                   5081:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5082:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5083:                                                 @personnel = @{$accessinfo->{$role}};
                   5084:                                             }
                   5085:                                         }
                   5086:                                     }
                   5087:                                 }
                   5088:                                 if ($curraccess eq 'none') {
                   5089:                                     next;
                   5090:                                 } elsif ($curraccess eq 'all') {
                   5091:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5092:                                 } elsif ($curraccess eq 'dh') {
                   5093:                                     if (grep(/^dh$/,@liveroles)) {
                   5094:                                         push(@possroles,$role);
                   5095:                                     } else {
                   5096:                                         next;
                   5097:                                     }
                   5098:                                 } elsif ($curraccess eq 'da') {
                   5099:                                     if (grep(/^da$/,@liveroles)) {
                   5100:                                         push(@possroles,$role);
                   5101:                                     } else {
                   5102:                                         next;
                   5103:                                     }
1.1172.2.89  raeburn  5104:                                 } elsif ($curraccess eq 'status') {
                   5105:                                     if (@okstatus) {
                   5106:                                         if (!@statuses) {
                   5107:                                             if (grep(/^default$/,@okstatus)) {
                   5108:                                                 push(@possroles,$role);
                   5109:                                             }
                   5110:                                         } else {
                   5111:                                             foreach my $status (@okstatus) {
                   5112:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5113:                                                     push(@possroles,$role);
                   5114:                                                     last;
                   5115:                                                 }
                   5116:                                             }
                   5117:                                         }
                   5118:                                     }
                   5119:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5120:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5121:                                         if ($curraccess eq 'exc') {
                   5122:                                             push(@possroles,$role);
                   5123:                                         }
                   5124:                                     } elsif ($curraccess eq 'inc') {
                   5125:                                         push(@possroles,$role);
                   5126:                                     }
                   5127:                                 }
                   5128:                             }
                   5129:                         }
                   5130:                     }
                   5131:                 }
                   5132:             }
                   5133:         }
                   5134:     }
                   5135:     unless (ref($description) eq 'HASH') {
                   5136:         if (ref($roles_by_num) eq 'ARRAY') {
                   5137:             my %desc;
                   5138:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5139:             $description = \%desc;
                   5140:         } else {
                   5141:             $description = {};
                   5142:         }
                   5143:     }
                   5144:     return (\@possroles,$description);
                   5145: }
                   5146: 
1.399     www      5147: # ----------------------------------------------------- Frontpage Announcements
                   5148: #
                   5149: #
                   5150: 
                   5151: sub postannounce {
                   5152:     my ($server,$text)=@_;
1.844     albertel 5153:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5154:     unless ($text=~/\w/) { $text=''; }
                   5155:     return &reply('setannounce:'.&escape($text),$server);
                   5156: }
                   5157: 
                   5158: sub getannounce {
1.448     albertel 5159: 
1.1172.2.96  raeburn  5160:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5161: 	my $announcement='';
1.800     albertel 5162: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5163: 	close($fh);
1.399     www      5164: 	if ($announcement=~/\w/) { 
                   5165: 	    return 
                   5166:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5167:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5168: 	} else {
                   5169: 	    return '';
                   5170: 	}
                   5171:     } else {
                   5172: 	return '';
                   5173:     }
1.351     www      5174: }
1.353     www      5175: 
                   5176: # ---------------------------------------------------------- Course ID routines
                   5177: # Deal with domain's nohist_courseid.db files
                   5178: #
                   5179: 
                   5180: sub courseidput {
1.921     raeburn  5181:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5182:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5183:     my $outcome;
                   5184:     if ($caller eq 'timeonly') {
                   5185:         my $cids = '';
                   5186:         foreach my $item (keys(%$storehash)) {
                   5187:             $cids.=&escape($item).'&';
                   5188:         }
                   5189:         $cids=~s/\&$//;
                   5190:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5191:                           $coursehome);       
                   5192:     } else {
                   5193:         my $items = '';
                   5194:         foreach my $item (keys(%$storehash)) {
                   5195:             $items.= &escape($item).'='.
                   5196:                      &freeze_escape($$storehash{$item}).'&';
                   5197:         }
                   5198:         $items=~s/\&$//;
                   5199:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5200:                           $coursehome);
1.918     raeburn  5201:     }
                   5202:     if ($outcome eq 'unknown_cmd') {
                   5203:         my $what;
                   5204:         foreach my $cid (keys(%$storehash)) {
                   5205:             $what .= &escape($cid).'=';
1.921     raeburn  5206:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5207:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5208:             }
                   5209:             $what =~ s/\:$/&/;
                   5210:         }
                   5211:         $what =~ s/\&$//;  
                   5212:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5213:     } else {
                   5214:         return $outcome;
                   5215:     }
1.353     www      5216: }
                   5217: 
                   5218: sub courseiddump {
1.921     raeburn  5219:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5220:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5221:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5222:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5223:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5224:     my $as_hash = 1;
                   5225:     my %returnhash;
                   5226:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5227:     my %libserv = &all_library();
                   5228:     foreach my $tryserver (keys(%libserv)) {
                   5229:         if ( (  $hostidflag == 1 
                   5230: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5231: 	     || (!defined($hostidflag)) ) {
                   5232: 
1.918     raeburn  5233: 	    if (($domfilter eq '') ||
                   5234: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5235:                 my $rep;
                   5236:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5237:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5238:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5239:                                 &escape($descfilter), &escape($instcodefilter),
                   5240:                                 &escape($ownerfilter), &escape($coursefilter),
                   5241:                                 &escape($typefilter), &escape($regexp_ok),
                   5242:                                 $as_hash, &escape($selfenrollonly),
                   5243:                                 &escape($catfilter), $showhidden, $caller,
                   5244:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5245:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5246:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5247:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5248:                 } else {
                   5249:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5250:                              $sincefilter.':'.&escape($descfilter).':'.
                   5251:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5252:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5253:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5254:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5255:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5256:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5257:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5258:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5259:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5260:                 }
                   5261: 
1.918     raeburn  5262:                 my @pairs=split(/\&/,$rep);
                   5263:                 foreach my $item (@pairs) {
                   5264:                     my ($key,$value)=split(/\=/,$item,2);
                   5265:                     $key = &unescape($key);
                   5266:                     next if ($key =~ /^error: 2 /);
                   5267:                     my $result = &thaw_unescape($value);
                   5268:                     if (ref($result) eq 'HASH') {
                   5269:                         $returnhash{$key}=$result;
                   5270:                     } else {
1.921     raeburn  5271:                         my @responses = split(/:/,$value);
                   5272:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5273:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5274:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5275:                         }
1.1008    raeburn  5276:                     }
1.353     www      5277:                 }
                   5278:             }
                   5279:         }
                   5280:     }
                   5281:     return %returnhash;
                   5282: }
                   5283: 
1.1055    raeburn  5284: sub courselastaccess {
                   5285:     my ($cdom,$cnum,$hostidref) = @_;
                   5286:     my %returnhash;
                   5287:     if ($cdom && $cnum) {
                   5288:         my $chome = &homeserver($cnum,$cdom);
                   5289:         if ($chome ne 'no_host') {
                   5290:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5291:             &extract_lastaccess(\%returnhash,$rep);
                   5292:         }
                   5293:     } else {
                   5294:         if (!$cdom) { $cdom=''; }
                   5295:         my %libserv = &all_library();
                   5296:         foreach my $tryserver (keys(%libserv)) {
                   5297:             if (ref($hostidref) eq 'ARRAY') {
                   5298:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5299:             } 
                   5300:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5301:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5302:                 &extract_lastaccess(\%returnhash,$rep);
                   5303:             }
                   5304:         }
                   5305:     }
                   5306:     return %returnhash;
                   5307: }
                   5308: 
                   5309: sub extract_lastaccess {
                   5310:     my ($returnhash,$rep) = @_;
                   5311:     if (ref($returnhash) eq 'HASH') {
                   5312:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5313:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5314:                  $rep eq '') {
                   5315:             my @pairs=split(/\&/,$rep);
                   5316:             foreach my $item (@pairs) {
                   5317:                 my ($key,$value)=split(/\=/,$item,2);
                   5318:                 $key = &unescape($key);
                   5319:                 next if ($key =~ /^error: 2 /);
                   5320:                 $returnhash->{$key} = &thaw_unescape($value);
                   5321:             }
                   5322:         }
                   5323:     }
                   5324:     return;
                   5325: }
                   5326: 
1.658     raeburn  5327: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5328: 
                   5329: sub dcmailput {
1.685     raeburn  5330:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5331:     my $status = &Apache::lonnet::critical(
1.740     www      5332:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5333:        &escape($message),$server);
1.662     raeburn  5334:     return $status;
                   5335: }
                   5336: 
1.658     raeburn  5337: sub dcmaildump {
                   5338:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5339:     my %returnhash=();
1.846     albertel 5340: 
                   5341:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5342:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5343:                                                          &escape($enddate).':';
                   5344: 	my @esc_senders=map { &escape($_)} @$senders;
                   5345: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5346: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5347:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5348:             if (($key) && ($value)) {
                   5349:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5350:             }
                   5351:         }
                   5352:     }
                   5353:     return %returnhash;
                   5354: }
1.662     raeburn  5355: # ---------------------------------------------------------- Domain roles
                   5356: 
                   5357: sub get_domain_roles {
                   5358:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5359:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5360:         $startdate = '.';
                   5361:     }
1.1018    raeburn  5362:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5363:         $enddate = '.';
                   5364:     }
1.922     raeburn  5365:     my $rolelist;
                   5366:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5367:         $rolelist = join('&',@{$roles});
1.922     raeburn  5368:     }
1.662     raeburn  5369:     my %personnel = ();
1.841     albertel 5370: 
                   5371:     my %servers = &get_servers($dom,'library');
                   5372:     foreach my $tryserver (keys(%servers)) {
                   5373: 	%{$personnel{$tryserver}}=();
                   5374: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5375: 					    &escape($startdate).':'.
                   5376: 					    &escape($enddate).':'.
                   5377: 					    &escape($rolelist), $tryserver))) {
                   5378: 	    my ($key,$value) = split(/\=/,$line,2);
                   5379: 	    if (($key) && ($value)) {
                   5380: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5381: 	    }
                   5382: 	}
1.662     raeburn  5383:     }
                   5384:     return %personnel;
                   5385: }
1.658     raeburn  5386: 
1.1172.2.89  raeburn  5387: sub get_active_domroles {
                   5388:     my ($dom,$roles) = @_;
                   5389:     return () unless (ref($roles) eq 'ARRAY');
                   5390:     my $now = time;
                   5391:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5392:     my %domroles;
                   5393:     foreach my $server (keys(%dompersonnel)) {
                   5394:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5395:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5396:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5397:         }
                   5398:     }
                   5399:     return %domroles;
                   5400: }
                   5401: 
1.1057    www      5402: # ----------------------------------------------------------- Interval timing 
1.149     www      5403: 
1.1153    www      5404: {
                   5405: # Caches needed for speedup of navmaps
                   5406: # We don't want to cache this for very long at all (5 seconds at most)
                   5407: # 
                   5408: # The user for whom we cache
                   5409: my $cachedkey='';
                   5410: # The cached times for this user
                   5411: my %cachedtimes=();
                   5412: # When this was last done
1.1172.2.66  raeburn  5413: my $cachedtime='';
1.1153    www      5414: 
                   5415: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5416:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5417:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5418:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5419:20):         (!$ignorecache)) {
1.1154    raeburn  5420:         return;
                   5421:     }
                   5422:     $cachedtime=time;
                   5423:     $cachedkey=$uname.':'.$udom;
                   5424:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5425: }
                   5426: 
1.504     albertel 5427: sub get_first_access {
1.1172.2.118.  .1(raebu 5428:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5429:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5430:     if ($argsymb) { $symb=$argsymb; }
                   5431:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5432:     if ($argmap) { $map = $argmap; }
1.926     albertel 5433:     if ($type eq 'course') {
                   5434: 	$res='course';
                   5435:     } elsif ($type eq 'map') {
1.588     albertel 5436: 	$res=&symbread($map);
                   5437:     } else {
                   5438: 	$res=$symb;
                   5439:     }
1.1172.2.118.  .1(raebu 5440:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5441:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5442: }
                   5443: 
                   5444: sub set_first_access {
1.1162    raeburn  5445:     my ($type,$interval)=@_;
1.790     albertel 5446:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5447:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5448:     if ($type eq 'course') {
                   5449: 	$res='course';
                   5450:     } elsif ($type eq 'map') {
1.588     albertel 5451: 	$res=&symbread($map);
                   5452:     } else {
                   5453: 	$res=$symb;
                   5454:     }
1.1153    www      5455:     $cachedkey='';
1.1162    raeburn  5456:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5457:     if ($firstaccess) {
                   5458:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5459:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5460:                  "in $courseid");
                   5461:         return 'already_set';
                   5462:     } else {
1.1162    raeburn  5463:         my $start = time;
                   5464: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5465:                           $udom,$uname);
                   5466:         if ($putres eq 'ok') {
                   5467:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5468:                  $udom,$uname); 
                   5469:             &appenv(
                   5470:                      {
                   5471:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5472:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5473:                      }
                   5474:                   );
1.1172.2.97  raeburn  5475:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5476:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5477:             }
1.1172.2.102  raeburn  5478:         } elsif ($putres ne 'refused') {
                   5479:             &logthis("Result: $putres when attempting to set first access time ".
                   5480:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5481:         }
                   5482:         return $putres;
1.505     albertel 5483:     }
                   5484:     return 'already_set';
1.504     albertel 5485: }
1.1153    www      5486: }
1.1172.2.32  raeburn  5487: 
                   5488: sub checkout {
                   5489:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5490:     my $now=time;
                   5491:     my $lonhost=$perlvar{'lonHostID'};
                   5492:     my $infostr=&escape(
                   5493:                  'CHECKOUTTOKEN&'.
                   5494:                  $tuname.'&'.
                   5495:                  $tudom.'&'.
                   5496:                  $tcrsid.'&'.
                   5497:                  $symb.'&'.
                   5498:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5499:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5500:     if ($token=~/^error\:/) {
                   5501:         &logthis("<font color=\"blue\">WARNING: ".
                   5502:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5503:                  "</font>");
                   5504:         return '';
                   5505:     }
                   5506: 
                   5507:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5508:     $token=~tr/a-z/A-Z/;
                   5509: 
                   5510:     my %infohash=('resource.0.outtoken' => $token,
                   5511:                   'resource.0.checkouttime' => $now,
                   5512:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5513: 
                   5514:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5515:        return '';
                   5516:     } else {
                   5517:         &logthis("<font color=\"blue\">WARNING: ".
                   5518:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5519:                  "</font>");
                   5520:     }
                   5521: 
                   5522:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5523:                          &escape('Checkout '.$infostr.' - '.
                   5524:                                                  $token)) ne 'ok') {
                   5525:         return '';
                   5526:     } else {
                   5527:         &logthis("<font color=\"blue\">WARNING: ".
                   5528:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5529:                  "</font>");
                   5530:     }
                   5531:     return $token;
                   5532: }
                   5533: 
                   5534: # ------------------------------------------------------------ Check in an item
                   5535: 
                   5536: sub checkin {
                   5537:     my $token=shift;
                   5538:     my $now=time;
                   5539:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5540:     $lonhost=~tr/A-Z/a-z/;
                   5541:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5542:     $dtoken=~s/\W/\_/g;
                   5543:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5544:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5545: 
                   5546:     unless (($tuname) && ($tudom)) {
                   5547:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5548:         return '';
                   5549:     }
                   5550: 
                   5551:     unless (&allowed('mgr',$tcrsid)) {
                   5552:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5553:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5554:         return '';
                   5555:     }
                   5556: 
                   5557:     my %infohash=('resource.0.intoken' => $token,
                   5558:                   'resource.0.checkintime' => $now,
                   5559:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5560: 
                   5561:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5562:        return '';
                   5563:     }
                   5564: 
                   5565:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5566:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5567:         return '';
                   5568:     }
                   5569: 
                   5570:     return ($symb,$tuname,$tudom,$tcrsid);
                   5571: }
                   5572: 
1.110     www      5573: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5574: 
                   5575: sub expirespread {
                   5576:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5577:     my $cid=$env{'request.course.id'}; 
1.110     www      5578:     if ($cid) {
                   5579:        my $now=time;
                   5580:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5581:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5582:                             $env{'course.'.$cid.'.num'}.
1.110     www      5583: 	        	    ':nohist_expirationdates:'.
                   5584:                             &escape($key).'='.$now,
1.620     albertel 5585:                             $env{'course.'.$cid.'.home'})
1.110     www      5586:     }
                   5587:     return 'ok';
1.14      www      5588: }
                   5589: 
1.109     www      5590: # ----------------------------------------------------- Devalidate Spreadsheets
                   5591: 
                   5592: sub devalidate {
1.325     www      5593:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5594:     my $cid=$env{'request.course.id'}; 
1.109     www      5595:     if ($cid) {
1.391     matthew  5596:         # delete the stored spreadsheets for
                   5597:         # - the student level sheet of this user in course's homespace
                   5598:         # - the assessment level sheet for this resource 
                   5599:         #   for this user in user's homespace
1.553     albertel 5600: 	# - current conditional state info
1.325     www      5601: 	my $key=$uname.':'.$udom.':';
1.109     www      5602:         my $status=
1.299     matthew  5603: 	    &del('nohist_calculatedsheets',
1.391     matthew  5604: 		 [$key.'studentcalc:'],
1.620     albertel 5605: 		 $env{'course.'.$cid.'.domain'},
                   5606: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5607: 		.' '.
                   5608: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5609: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5610:         unless ($status eq 'ok ok') {
                   5611:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5612:                     $uname.' at '.$udom.' for '.
1.109     www      5613: 		    $symb.': '.$status);
1.133     albertel 5614:         }
1.553     albertel 5615: 	&delenv('user.state.'.$cid);
1.109     www      5616:     }
                   5617: }
                   5618: 
1.265     albertel 5619: sub get_scalar {
                   5620:     my ($string,$end) = @_;
                   5621:     my $value;
                   5622:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5623: 	$value = $1;
                   5624:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5625: 	$value = $1;
                   5626:     }
                   5627:     return &unescape($value);
                   5628: }
                   5629: 
                   5630: sub array2str {
                   5631:   my (@array) = @_;
                   5632:   my $result=&arrayref2str(\@array);
                   5633:   $result=~s/^__ARRAY_REF__//;
                   5634:   $result=~s/__END_ARRAY_REF__$//;
                   5635:   return $result;
                   5636: }
                   5637: 
1.204     albertel 5638: sub arrayref2str {
                   5639:   my ($arrayref) = @_;
1.265     albertel 5640:   my $result='__ARRAY_REF__';
1.204     albertel 5641:   foreach my $elem (@$arrayref) {
1.265     albertel 5642:     if(ref($elem) eq 'ARRAY') {
                   5643:       $result.=&arrayref2str($elem).'&';
                   5644:     } elsif(ref($elem) eq 'HASH') {
                   5645:       $result.=&hashref2str($elem).'&';
                   5646:     } elsif(ref($elem)) {
                   5647:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5648:     } else {
                   5649:       $result.=&escape($elem).'&';
                   5650:     }
                   5651:   }
                   5652:   $result=~s/\&$//;
1.265     albertel 5653:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5654:   return $result;
                   5655: }
                   5656: 
1.168     albertel 5657: sub hash2str {
1.204     albertel 5658:   my (%hash) = @_;
                   5659:   my $result=&hashref2str(\%hash);
1.265     albertel 5660:   $result=~s/^__HASH_REF__//;
                   5661:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5662:   return $result;
                   5663: }
                   5664: 
                   5665: sub hashref2str {
                   5666:   my ($hashref)=@_;
1.265     albertel 5667:   my $result='__HASH_REF__';
1.800     albertel 5668:   foreach my $key (sort(keys(%$hashref))) {
                   5669:     if (ref($key) eq 'ARRAY') {
                   5670:       $result.=&arrayref2str($key).'=';
                   5671:     } elsif (ref($key) eq 'HASH') {
                   5672:       $result.=&hashref2str($key).'=';
                   5673:     } elsif (ref($key)) {
1.265     albertel 5674:       $result.='=';
1.800     albertel 5675:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5676:     } else {
1.1132    raeburn  5677: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5678:     }
                   5679: 
1.800     albertel 5680:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5681:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5682:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5683:       $result.=&hashref2str($hashref->{$key}).'&';
                   5684:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5685:        $result.='&';
1.800     albertel 5686:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5687:     } else {
1.800     albertel 5688:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5689:     }
                   5690:   }
1.168     albertel 5691:   $result=~s/\&$//;
1.265     albertel 5692:   $result .= '__END_HASH_REF__';
1.168     albertel 5693:   return $result;
                   5694: }
                   5695: 
                   5696: sub str2hash {
1.265     albertel 5697:     my ($string)=@_;
                   5698:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5699:     return %$hash;
                   5700: }
                   5701: 
                   5702: sub str2hashref {
1.168     albertel 5703:   my ($string) = @_;
1.265     albertel 5704: 
                   5705:   my %hash;
                   5706: 
                   5707:   if($string !~ /^__HASH_REF__/) {
                   5708:       if (! ($string eq '' || !defined($string))) {
                   5709: 	  $hash{'error'}='Not hash reference';
                   5710:       }
                   5711:       return (\%hash, $string);
                   5712:   }
                   5713: 
                   5714:   $string =~ s/^__HASH_REF__//;
                   5715: 
                   5716:   while($string !~ /^__END_HASH_REF__/) {
                   5717:       #key
                   5718:       my $key='';
                   5719:       if($string =~ /^__HASH_REF__/) {
                   5720:           ($key, $string)=&str2hashref($string);
                   5721:           if(defined($key->{'error'})) {
                   5722:               $hash{'error'}='Bad data';
                   5723:               return (\%hash, $string);
                   5724:           }
                   5725:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5726:           ($key, $string)=&str2arrayref($string);
                   5727:           if($key->[0] eq 'Array reference error') {
                   5728:               $hash{'error'}='Bad data';
                   5729:               return (\%hash, $string);
                   5730:           }
                   5731:       } else {
                   5732:           $string =~ s/^(.*?)=//;
1.267     albertel 5733: 	  $key=&unescape($1);
1.265     albertel 5734:       }
                   5735:       $string =~ s/^=//;
                   5736: 
                   5737:       #value
                   5738:       my $value='';
                   5739:       if($string =~ /^__HASH_REF__/) {
                   5740:           ($value, $string)=&str2hashref($string);
                   5741:           if(defined($value->{'error'})) {
                   5742:               $hash{'error'}='Bad data';
                   5743:               return (\%hash, $string);
                   5744:           }
                   5745:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5746:           ($value, $string)=&str2arrayref($string);
                   5747:           if($value->[0] eq 'Array reference error') {
                   5748:               $hash{'error'}='Bad data';
                   5749:               return (\%hash, $string);
                   5750:           }
                   5751:       } else {
                   5752: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5753:       }
                   5754:       $string =~ s/^&//;
                   5755: 
                   5756:       $hash{$key}=$value;
1.204     albertel 5757:   }
1.265     albertel 5758: 
                   5759:   $string =~ s/^__END_HASH_REF__//;
                   5760: 
                   5761:   return (\%hash, $string);
1.204     albertel 5762: }
                   5763: 
                   5764: sub str2array {
1.265     albertel 5765:     my ($string)=@_;
                   5766:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5767:     return @$array;
                   5768: }
                   5769: 
                   5770: sub str2arrayref {
1.204     albertel 5771:   my ($string) = @_;
1.265     albertel 5772:   my @array;
                   5773: 
                   5774:   if($string !~ /^__ARRAY_REF__/) {
                   5775:       if (! ($string eq '' || !defined($string))) {
                   5776: 	  $array[0]='Array reference error';
                   5777:       }
                   5778:       return (\@array, $string);
                   5779:   }
                   5780: 
                   5781:   $string =~ s/^__ARRAY_REF__//;
                   5782: 
                   5783:   while($string !~ /^__END_ARRAY_REF__/) {
                   5784:       my $value='';
                   5785:       if($string =~ /^__HASH_REF__/) {
                   5786:           ($value, $string)=&str2hashref($string);
                   5787:           if(defined($value->{'error'})) {
                   5788:               $array[0] ='Array reference error';
                   5789:               return (\@array, $string);
                   5790:           }
                   5791:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5792:           ($value, $string)=&str2arrayref($string);
                   5793:           if($value->[0] eq 'Array reference error') {
                   5794:               $array[0] ='Array reference error';
                   5795:               return (\@array, $string);
                   5796:           }
                   5797:       } else {
                   5798: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5799:       }
                   5800:       $string =~ s/^&//;
                   5801: 
                   5802:       push(@array, $value);
1.191     harris41 5803:   }
1.265     albertel 5804: 
                   5805:   $string =~ s/^__END_ARRAY_REF__//;
                   5806: 
                   5807:   return (\@array, $string);
1.168     albertel 5808: }
                   5809: 
1.167     albertel 5810: # -------------------------------------------------------------------Temp Store
                   5811: 
1.168     albertel 5812: sub tmpreset {
                   5813:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5814:   if (!$symb) {
                   5815:     $symb=&symbread();
1.620     albertel 5816:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5817:   }
                   5818:   $symb=escape($symb);
                   5819: 
1.620     albertel 5820:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5821:   $namespace=~s/\//\_/g;
                   5822:   $namespace=~s/\W//g;
                   5823: 
1.620     albertel 5824:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5825:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5826:   if ($domain eq 'public' && $stuname eq 'public') {
                   5827:       $stuname=$ENV{'REMOTE_ADDR'};
                   5828:   }
1.1117    foxr     5829:   my $path=LONCAPA::tempdir();
1.168     albertel 5830:   my %hash;
                   5831:   if (tie(%hash,'GDBM_File',
                   5832: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5833: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5834:     foreach my $key (keys(%hash)) {
1.180     albertel 5835:       if ($key=~ /:$symb/) {
1.168     albertel 5836: 	delete($hash{$key});
                   5837:       }
                   5838:     }
                   5839:   }
                   5840: }
                   5841: 
1.167     albertel 5842: sub tmpstore {
1.168     albertel 5843:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5844: 
                   5845:   if (!$symb) {
                   5846:     $symb=&symbread();
1.620     albertel 5847:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5848:   }
                   5849:   $symb=escape($symb);
                   5850: 
                   5851:   if (!$namespace) {
                   5852:     # I don't think we would ever want to store this for a course.
                   5853:     # it seems this will only be used if we don't have a course.
1.620     albertel 5854:     #$namespace=$env{'request.course.id'};
1.168     albertel 5855:     #if (!$namespace) {
1.620     albertel 5856:       $namespace=$env{'request.state'};
1.168     albertel 5857:     #}
                   5858:   }
                   5859:   $namespace=~s/\//\_/g;
                   5860:   $namespace=~s/\W//g;
1.620     albertel 5861:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5862:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5863:   if ($domain eq 'public' && $stuname eq 'public') {
                   5864:       $stuname=$ENV{'REMOTE_ADDR'};
                   5865:   }
1.168     albertel 5866:   my $now=time;
                   5867:   my %hash;
1.1117    foxr     5868:   my $path=LONCAPA::tempdir();
1.168     albertel 5869:   if (tie(%hash,'GDBM_File',
                   5870: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5871: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5872:     $hash{"version:$symb"}++;
                   5873:     my $version=$hash{"version:$symb"};
                   5874:     my $allkeys=''; 
                   5875:     foreach my $key (keys(%$storehash)) {
                   5876:       $allkeys.=$key.':';
1.591     albertel 5877:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5878:     }
                   5879:     $hash{"$version:$symb:timestamp"}=$now;
                   5880:     $allkeys.='timestamp';
                   5881:     $hash{"$version:keys:$symb"}=$allkeys;
                   5882:     if (untie(%hash)) {
                   5883:       return 'ok';
                   5884:     } else {
                   5885:       return "error:$!";
                   5886:     }
                   5887:   } else {
                   5888:     return "error:$!";
                   5889:   }
                   5890: }
1.167     albertel 5891: 
1.168     albertel 5892: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5893: 
1.168     albertel 5894: sub tmprestore {
                   5895:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5896: 
1.168     albertel 5897:   if (!$symb) {
                   5898:     $symb=&symbread();
1.620     albertel 5899:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5900:   }
                   5901:   $symb=escape($symb);
                   5902: 
1.620     albertel 5903:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5904: 
1.620     albertel 5905:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5906:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5907:   if ($domain eq 'public' && $stuname eq 'public') {
                   5908:       $stuname=$ENV{'REMOTE_ADDR'};
                   5909:   }
1.168     albertel 5910:   my %returnhash;
                   5911:   $namespace=~s/\//\_/g;
                   5912:   $namespace=~s/\W//g;
                   5913:   my %hash;
1.1117    foxr     5914:   my $path=LONCAPA::tempdir();
1.168     albertel 5915:   if (tie(%hash,'GDBM_File',
                   5916: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5917: 	  &GDBM_READER(),0640)) {
1.168     albertel 5918:     my $version=$hash{"version:$symb"};
                   5919:     $returnhash{'version'}=$version;
                   5920:     my $scope;
                   5921:     for ($scope=1;$scope<=$version;$scope++) {
                   5922:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5923:       my @keys=split(/:/,$vkeys);
                   5924:       my $key;
                   5925:       $returnhash{"$scope:keys"}=$vkeys;
                   5926:       foreach $key (@keys) {
1.591     albertel 5927: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5928: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5929:       }
                   5930:     }
1.168     albertel 5931:     if (!(untie(%hash))) {
                   5932:       return "error:$!";
                   5933:     }
                   5934:   } else {
                   5935:     return "error:$!";
                   5936:   }
                   5937:   return %returnhash;
1.167     albertel 5938: }
                   5939: 
1.9       www      5940: # ----------------------------------------------------------------------- Store
                   5941: 
                   5942: sub store {
1.1172.2.64  raeburn  5943:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5944:     my $home='';
                   5945: 
1.168     albertel 5946:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5947: 
1.213     www      5948:     $symb=&symbclean($symb);
1.122     albertel 5949:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5950: 
1.620     albertel 5951:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5952:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5953: 
                   5954:     &devalidate($symb,$stuname,$domain);
1.109     www      5955: 
                   5956:     $symb=escape($symb);
1.187     www      5957:     if (!$namespace) { 
1.620     albertel 5958:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5959:           return ''; 
                   5960:        } 
                   5961:     }
1.620     albertel 5962:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5963: 
                   5964:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5965:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5966: 
1.12      www      5967:     my $namevalue='';
1.800     albertel 5968:     foreach my $key (keys(%$storehash)) {
                   5969:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5970:     }
1.12      www      5971:     $namevalue=~s/\&$//;
1.187     www      5972:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5973:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5974: }
                   5975: 
1.47      www      5976: # -------------------------------------------------------------- Critical Store
                   5977: 
                   5978: sub cstore {
1.1172.2.64  raeburn  5979:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5980:     my $home='';
                   5981: 
1.168     albertel 5982:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5983: 
1.213     www      5984:     $symb=&symbclean($symb);
1.122     albertel 5985:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5986: 
1.620     albertel 5987:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5988:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5989: 
                   5990:     &devalidate($symb,$stuname,$domain);
1.109     www      5991: 
                   5992:     $symb=escape($symb);
1.187     www      5993:     if (!$namespace) { 
1.620     albertel 5994:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5995:           return ''; 
                   5996:        } 
                   5997:     }
1.620     albertel 5998:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5999: 
                   6000:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6001:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6002: 
1.47      www      6003:     my $namevalue='';
1.800     albertel 6004:     foreach my $key (keys(%$storehash)) {
                   6005:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6006:     }
1.47      www      6007:     $namevalue=~s/\&$//;
1.187     www      6008:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6009:     return critical
1.1172.2.64  raeburn  6010:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6011: }
                   6012: 
1.9       www      6013: # --------------------------------------------------------------------- Restore
                   6014: 
                   6015: sub restore {
1.124     www      6016:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6017:     my $home='';
                   6018: 
1.168     albertel 6019:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6020: 
1.122     albertel 6021:     if (!$symb) {
1.1172.2.26  raeburn  6022:         return if ($namespace eq 'courserequests');
                   6023:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6024:     } else {
1.1172.2.26  raeburn  6025:         unless ($namespace eq 'courserequests') {
                   6026:             $symb=&escape(&symbclean($symb));
                   6027:         }
1.122     albertel 6028:     }
1.188     www      6029:     if (!$namespace) { 
1.620     albertel 6030:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6031:           return ''; 
                   6032:        } 
                   6033:     }
1.620     albertel 6034:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6035:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6036:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6037:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6038: 
1.12      www      6039:     my %returnhash=();
1.800     albertel 6040:     foreach my $line (split(/\&/,$answer)) {
                   6041: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6042:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6043:     }
1.75      www      6044:     my $version;
                   6045:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6046:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6047:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6048:        }
1.75      www      6049:     }
1.13      www      6050:     return %returnhash;
1.34      www      6051: }
                   6052: 
                   6053: # ---------------------------------------------------------- Course Description
1.1118    foxr     6054: #
                   6055: #  
1.34      www      6056: 
                   6057: sub coursedescription {
1.731     albertel 6058:     my ($courseid,$args)=@_;
1.34      www      6059:     $courseid=~s/^\///;
1.49      www      6060:     $courseid=~s/\_/\//g;
1.34      www      6061:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6062:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6063:     my $normalid=$cdomain.'_'.$cnum;
                   6064:     # need to always cache even if we get errors otherwise we keep 
                   6065:     # trying and trying and trying to get the course description.
                   6066:     my %envhash=();
                   6067:     my %returnhash=();
1.731     albertel 6068:     
                   6069:     my $expiretime=600;
                   6070:     if ($env{'request.course.id'} eq $normalid) {
                   6071: 	$expiretime=120;
                   6072:     }
                   6073: 
                   6074:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6075:     if (!$args->{'freshen_cache'}
                   6076: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6077: 	foreach my $key (keys(%env)) {
                   6078: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6079: 	    my ($setting) = $1;
                   6080: 	    $returnhash{$setting} = $env{$key};
                   6081: 	}
                   6082: 	return %returnhash;
                   6083:     }
                   6084: 
1.1118    foxr     6085:     # get the data again
                   6086: 
1.731     albertel 6087:     if (!$args->{'one_time'}) {
                   6088: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6089:     }
1.811     albertel 6090: 
1.34      www      6091:     if ($chome ne 'no_host') {
1.302     albertel 6092:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6093:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6094: 	   my $username = $env{'user.name'}; # Defult username
                   6095: 	   if(defined $args->{'user'}) {
                   6096: 	       $username = $args->{'user'};
                   6097: 	   }
1.129     albertel 6098:            $returnhash{'home'}= $chome;
                   6099: 	   $returnhash{'domain'} = $cdomain;
                   6100: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6101:            if (!defined($returnhash{'type'})) {
                   6102:                $returnhash{'type'} = 'Course';
                   6103:            }
1.130     albertel 6104:            while (my ($name,$value) = each %returnhash) {
1.53      www      6105:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6106:            }
1.270     www      6107:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6108:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6109: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6110:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6111:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6112:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6113:        }
                   6114:     }
1.731     albertel 6115:     if (!$args->{'one_time'}) {
1.949     raeburn  6116: 	&appenv(\%envhash);
1.731     albertel 6117:     }
1.302     albertel 6118:     return %returnhash;
1.461     www      6119: }
                   6120: 
1.1080    raeburn  6121: sub update_released_required {
                   6122:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6123:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6124:         $cid = $env{'request.course.id'};
                   6125:         $cdom = $env{'course.'.$cid.'.domain'};
                   6126:         $cnum = $env{'course.'.$cid.'.num'};
                   6127:         $chome = $env{'course.'.$cid.'.home'};
                   6128:     }
                   6129:     if ($needsrelease) {
                   6130:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6131:         my $needsupdate;
                   6132:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6133:             $needsupdate = 1;
                   6134:         } else {
                   6135:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6136:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6137:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6138:                 $needsupdate = 1;
                   6139:             }
                   6140:         }
                   6141:         if ($needsupdate) {
                   6142:             my %needshash = (
                   6143:                              'internal.releaserequired' => $needsrelease,
                   6144:                             );
                   6145:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6146:             if ($putresult eq 'ok') {
                   6147:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6148:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6149:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6150:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6151:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6152:                 }
                   6153:             }
                   6154:         }
                   6155:     }
                   6156:     return;
                   6157: }
                   6158: 
1.461     www      6159: # -------------------------------------------------See if a user is privileged
                   6160: 
                   6161: sub privileged {
1.1172.2.23  raeburn  6162:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6163:     my $now = time;
1.1172.2.23  raeburn  6164:     my $roles;
                   6165:     if (ref($possroles) eq 'ARRAY') {
                   6166:         $roles = $possroles;
                   6167:     } else {
                   6168:         $roles = ['dc','su'];
                   6169:     }
                   6170:     if (ref($possdomains) eq 'ARRAY') {
                   6171:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6172:         foreach my $dom (@{$possdomains}) {
                   6173:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6174:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6175:                 foreach my $role (@{$roles}) {
                   6176:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6177:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6178:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6179:                             return 1 unless (($end && $end < $now) ||
                   6180:                                              ($start && $start > $now));
                   6181:                         }
                   6182:                     }
                   6183:                 }
                   6184:             }
                   6185:         }
                   6186:     } else {
                   6187:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6188:         my $now = time;
1.1170    droeschl 6189: 
1.1172.2.58  raeburn  6190:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6191:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6192:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6193:                 return 1 unless ($tend && $tend < $now)
                   6194:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6195:             }
1.1172.2.23  raeburn  6196:         }
                   6197:     }
1.461     www      6198:     return 0;
1.9       www      6199: }
1.1       albertel 6200: 
1.1172.2.23  raeburn  6201: sub privileged_by_domain {
                   6202:     my ($domains,$roles) = @_;
                   6203:     my %privileged = ();
                   6204:     my $cachetime = 60*60*24;
                   6205:     my $now = time;
                   6206:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6207:         return %privileged;
                   6208:     }
                   6209:     foreach my $dom (@{$domains}) {
                   6210:         next if (ref($privileged{$dom}) eq 'HASH');
                   6211:         my $needroles;
                   6212:         foreach my $role (@{$roles}) {
                   6213:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6214:             if (defined($cached)) {
                   6215:                 if (ref($result) eq 'HASH') {
                   6216:                     $privileged{$dom}{$role} = $result;
                   6217:                 }
                   6218:             } else {
                   6219:                 $needroles = 1;
                   6220:             }
                   6221:         }
                   6222:         if ($needroles) {
                   6223:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6224:             $privileged{$dom} = {};
                   6225:             foreach my $server (keys(%dompersonnel)) {
                   6226:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6227:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6228:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6229:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6230:                         next if ($end && $end < $now);
                   6231:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6232:                             $dompersonnel{$server}{$item};
                   6233:                     }
                   6234:                 }
                   6235:             }
                   6236:             if (ref($privileged{$dom}) eq 'HASH') {
                   6237:                 foreach my $role (@{$roles}) {
                   6238:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6239:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6240:                     } else {
                   6241:                         my %hash = ();
                   6242:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6243:                     }
                   6244:                 }
                   6245:             }
                   6246:         }
                   6247:     }
                   6248:     return %privileged;
                   6249: }
                   6250: 
1.103     harris41 6251: # -------------------------------------------------------- Get user privileges
1.11      www      6252: 
                   6253: sub rolesinit {
1.1169    droeschl 6254:     my ($domain, $username) = @_;
                   6255:     my %userroles = ('user.login.time' => time);
                   6256:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6257: 
                   6258:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6259:     # also, blocking can be triggered by an activating timer
                   6260:     # it's saved in the user's %env.
                   6261:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6262:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6263:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6264:         %timerintchk, %timerintenv);
                   6265: 
1.1162    raeburn  6266:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6267:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6268:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6269:     }
1.1169    droeschl 6270: 
1.1162    raeburn  6271:     foreach my $key (keys(%timerinterval)) {
                   6272:         my ($cid,$rest) = split(/\0/,$key);
                   6273:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6274:     }
1.1169    droeschl 6275: 
1.11      www      6276:     my %allroles=();
1.1162    raeburn  6277:     my %allgroups=();
1.11      www      6278: 
1.1172.2.58  raeburn  6279:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6280:         my $role = $rolesdump{$area};
                   6281:         $area =~ s/\_\w\w$//;
                   6282: 
                   6283:         my ($trole, $tend, $tstart, $group_privs);
                   6284: 
                   6285:         if ($role =~ /^cr/) {
                   6286:         # Custom role, defined by a user 
                   6287:         # e.g., user.role.cr/msu/smith/mynewrole
                   6288:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6289:                 $trole = $1;
                   6290:                 ($tend, $tstart) = split('_', $2);
                   6291:             } else {
                   6292:                 $trole = $role;
                   6293:             }
                   6294:         } elsif ($role =~ m|^gr/|) {
                   6295:         # Role of member in a group, defined within a course/community
                   6296:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6297:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6298:             next if $tstart eq '-1';
                   6299:             ($trole, $group_privs) = split(/\//, $trole);
                   6300:             $group_privs = &unescape($group_privs);
                   6301:         } else {
                   6302:         # Just a normal role, defined in roles.tab
                   6303:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6304:         }
                   6305: 
                   6306:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6307:                  $username);
                   6308:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6309: 
                   6310:         # role expired or not available yet?
                   6311:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6312:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6313: 
                   6314:         next if $area eq '' or $trole eq '';
                   6315: 
                   6316:         my $spec = "$trole.$area";
                   6317:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6318: 
                   6319:         if ($trole =~ /^cr\//) {
                   6320:         # Custom role, defined by a user
                   6321:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6322:         } elsif ($trole eq 'gr') {
                   6323:         # Role of a member in a group, defined within a course/community
                   6324:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6325:             next;
                   6326:         } else {
                   6327:         # Normal role, defined in roles.tab
                   6328:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6329:         }
                   6330: 
                   6331:         my $cid = $tdomain.'_'.$trest;
                   6332:         unless ($firstaccchk{$cid}) {
                   6333:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6334:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6335:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6336:                         $coursetimerstarts{$cid}{$item}; 
                   6337:                 }
                   6338:             }
                   6339:             $firstaccchk{$cid} = 1;
                   6340:         }
                   6341:         unless ($timerintchk{$cid}) {
                   6342:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6343:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6344:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6345:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6346:                 }
1.12      www      6347:             }
1.1169    droeschl 6348:             $timerintchk{$cid} = 1;
1.191     harris41 6349:         }
1.11      www      6350:     }
1.1169    droeschl 6351: 
1.1172.2.91  raeburn  6352:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6353:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6354:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6355:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6356: 
1.1162    raeburn  6357:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6358: }
                   6359: 
1.567     raeburn  6360: sub set_arearole {
1.1172.2.19  raeburn  6361:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6362:     unless ($nolog) {
1.567     raeburn  6363: # log the associated role with the area
1.1172.2.19  raeburn  6364:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6365:     }
1.743     albertel 6366:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6367: }
                   6368: 
                   6369: sub custom_roleprivs {
                   6370:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6371:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6372:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6373:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6374:         my ($rdummy,$roledef)=
                   6375:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6376:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6377:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6378:             if (defined($syspriv)) {
1.1043    raeburn  6379:                 if ($trest =~ /^$match_community$/) {
                   6380:                     $syspriv =~ s/bre\&S//; 
                   6381:                 }
1.567     raeburn  6382:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6383:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6384:             }
                   6385:             if ($tdomain ne '') {
                   6386:                 if (defined($dompriv)) {
                   6387:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6388:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6389:                 }
                   6390:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6391:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6392:                         my $rolename = $1;
                   6393:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6394:                     }
1.567     raeburn  6395:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6396:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6397:                 }
                   6398:             }
                   6399:         }
                   6400:     }
                   6401: }
                   6402: 
1.1172.2.89  raeburn  6403: sub course_adhocrole_privs {
                   6404:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6405:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6406:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6407:         my (%currprivs,%storeprivs);
                   6408:         foreach my $item (split(/:/,$coursepriv)) {
                   6409:             my ($priv,$restrict) = split(/\&/,$item);
                   6410:             $currprivs{$priv} = $restrict;
                   6411:         }
                   6412:         my (%possadd,%possremove,%full);
                   6413:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6414:             my ($priv,$restrict)=split(/\&/,$item);
                   6415:             $full{$priv} = $restrict;
                   6416:         }
                   6417:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6418:              next if ($item eq '');
                   6419:              my ($rule,$rest) = split(/=/,$item);
                   6420:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6421:              foreach my $priv (split(/:/,$rest)) {
                   6422:                  if ($priv ne '') {
                   6423:                      if ($rule eq 'off') {
                   6424:                          $possremove{$priv} = 1;
                   6425:                      } else {
                   6426:                          $possadd{$priv} = 1;
                   6427:                      }
                   6428:                  }
                   6429:              }
                   6430:          }
                   6431:          foreach my $priv (sort(keys(%full))) {
                   6432:              if (exists($currprivs{$priv})) {
                   6433:                  unless (exists($possremove{$priv})) {
                   6434:                      $storeprivs{$priv} = $currprivs{$priv};
                   6435:                  }
                   6436:              } elsif (exists($possadd{$priv})) {
                   6437:                  $storeprivs{$priv} = $full{$priv};
                   6438:              }
                   6439:          }
                   6440:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6441:      }
                   6442:      return $coursepriv;
                   6443: }
                   6444: 
1.678     raeburn  6445: sub group_roleprivs {
                   6446:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6447:     my $access = 1;
                   6448:     my $now = time;
                   6449:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6450:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6451:     if ($access) {
1.811     albertel 6452:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6453:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6454:     }
                   6455: }
1.567     raeburn  6456: 
                   6457: sub standard_roleprivs {
                   6458:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6459:     if (defined($pr{$trole.':s'})) {
                   6460:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6461:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6462:     }
                   6463:     if ($tdomain ne '') {
                   6464:         if (defined($pr{$trole.':d'})) {
                   6465:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6466:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6467:         }
                   6468:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6469:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6470:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6471:         }
                   6472:     }
                   6473: }
                   6474: 
                   6475: sub set_userprivs {
1.1064    raeburn  6476:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6477:     my $author=0;
                   6478:     my $adv=0;
1.1172.2.91  raeburn  6479:     my $rar=0;
1.678     raeburn  6480:     my %grouproles = ();
                   6481:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6482:         my @groupkeys; 
1.1000    raeburn  6483:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6484:             push(@groupkeys,$role);
                   6485:         }
                   6486:         if (ref($groups_roles) eq 'HASH') {
                   6487:             foreach my $key (keys(%{$groups_roles})) {
                   6488:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6489:                     push(@groupkeys,$key);
                   6490:                 }
                   6491:             }
                   6492:         }
                   6493:         if (@groupkeys > 0) {
                   6494:             foreach my $role (@groupkeys) {
                   6495:                 my ($trole,$area,$sec,$extendedarea);
                   6496:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6497:                     $trole = $1;
                   6498:                     $area = $2;
                   6499:                     $sec = $3;
                   6500:                     $extendedarea = $area.$sec;
                   6501:                     if (exists($$allgroups{$area})) {
                   6502:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6503:                             my $spec = $trole.'.'.$extendedarea;
                   6504:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6505:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6506:                         }
1.678     raeburn  6507:                     }
                   6508:                 }
                   6509:             }
                   6510:         }
                   6511:     }
1.800     albertel 6512:     foreach my $group (keys(%grouproles)) {
                   6513:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6514:     }
1.800     albertel 6515:     foreach my $role (keys(%{$allroles})) {
                   6516:         my %thesepriv;
1.941     raeburn  6517:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6518:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6519:             if ($item ne '') {
                   6520:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6521:                 if ($restrictions eq '') {
                   6522:                     $thesepriv{$privilege}='F';
                   6523:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6524:                     $thesepriv{$privilege}.=$restrictions;
                   6525:                 }
                   6526:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6527:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6528:             }
                   6529:         }
                   6530:         my $thesestr='';
1.1104    raeburn  6531:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6532: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6533: 	}
                   6534:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6535:     }
1.1172.2.91  raeburn  6536:     return ($author,$adv,$rar);
1.567     raeburn  6537: }
                   6538: 
1.994     raeburn  6539: sub role_status {
1.1104    raeburn  6540:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6541:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6542:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6543:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6544:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6545:             $$where = '/'.$two;
1.994     raeburn  6546:             $$trolecode=$$role.'.'.$$where;
                   6547:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6548:             $$tstatus='is';
1.1104    raeburn  6549:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6550:                 $$tstatus='future';
1.1034    raeburn  6551:                 if ($$tstart<$now) {
                   6552:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6553:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6554:                             my (%allroles,%allgroups,$group_privs,
                   6555:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6556:                             my %userroles = (
                   6557:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6558:                             );
1.1064    raeburn  6559:                             @rolecodes = ('cm'); 
1.1002    raeburn  6560:                             my $spec=$$role.'.'.$$where;
                   6561:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6562:                             if ($$role =~ /^cr\//) {
                   6563:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6564:                                 push(@rolecodes,'cr');
1.1002    raeburn  6565:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6566:                                 push(@rolecodes,$$role);
1.1002    raeburn  6567:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6568:                                                     $env{'user.name'});
1.1064    raeburn  6569:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6570:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6571:                                 $group_privs = &unescape($group_privs);
                   6572:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6573:                                 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  6574:                                 &get_groups_roles($tdomain,$trest,
                   6575:                                                   \%course_roles,\@rolecodes,
                   6576:                                                   \%groups_roles);
1.1002    raeburn  6577:                             } else {
1.1064    raeburn  6578:                                 push(@rolecodes,$$role);
1.1002    raeburn  6579:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6580:                             }
1.1172.2.91  raeburn  6581:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6582:                                                                    \%groups_roles);
1.1064    raeburn  6583:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6584:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6585:                         }
                   6586:                     }
1.1034    raeburn  6587:                     $$tstatus = 'is';
1.1002    raeburn  6588:                 }
1.994     raeburn  6589:             }
                   6590:             if ($$tend) {
1.1104    raeburn  6591:                 if ($$tend<$update) {
1.994     raeburn  6592:                     $$tstatus='expired';
                   6593:                 } elsif ($$tend<$now) {
                   6594:                     $$tstatus='will_not';
                   6595:                 }
                   6596:             }
                   6597:         }
                   6598:     }
                   6599: }
                   6600: 
1.1104    raeburn  6601: sub get_groups_roles {
                   6602:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6603:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6604:                   (ref($rolecodes) eq 'ARRAY') && 
                   6605:                   (ref($groups_roles) eq 'HASH')); 
                   6606:     if (keys(%{$cdom_courseroles}) > 0) {
                   6607:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6608:         if ($cdom ne '' && $cnum ne '') {
                   6609:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6610:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6611:                     my $crsrole = $1;
                   6612:                     my $crssec = $2;
                   6613:                     if ($crsrole =~ /^cr/) {
                   6614:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6615:                             push(@{$rolecodes},'cr');
                   6616:                         }
                   6617:                     } else {
                   6618:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6619:                             push(@{$rolecodes},$crsrole);
                   6620:                         }
                   6621:                     }
                   6622:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6623:                     if ($crssec ne '') {
                   6624:                         $rolekey .= "/$crssec";
                   6625:                     }
                   6626:                     $rolekey .= './';
                   6627:                     $groups_roles->{$rolekey} = $rolecodes;
                   6628:                 }
                   6629:             }
                   6630:         }
                   6631:     }
                   6632:     return;
                   6633: }
                   6634: 
                   6635: sub delete_env_groupprivs {
                   6636:     my ($where,$courseroles,$possroles) = @_;
                   6637:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6638:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6639:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6640:         %{$courseroles->{$udom}} =
                   6641:             &get_my_roles('','','userroles',['active'],
                   6642:                           $possroles,[$udom],1);
                   6643:     }
                   6644:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6645:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6646:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6647:             my $area = '/'.$cdom.'/'.$cnum;
                   6648:             my $privkey = "user.priv.$crsrole.$area";
                   6649:             if ($crssec ne '') {
                   6650:                 $privkey .= '/'.$crssec;
                   6651:             }
                   6652:             $privkey .= ".$area/$group";
                   6653:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6654:         }
                   6655:     }
                   6656:     return;
                   6657: }
                   6658: 
1.994     raeburn  6659: sub check_adhoc_privs {
1.1172.2.86  raeburn  6660:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6661:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6662:     if ($sec) {
                   6663:         $cckey .= '/'.$sec;
                   6664:     }
1.1172.2.9  raeburn  6665:     my $setprivs;
1.994     raeburn  6666:     if ($env{$cckey}) {
                   6667:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6668:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6669:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6670:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6671:             $setprivs = 1;
1.994     raeburn  6672:         }
                   6673:     } else {
1.1172.2.87  raeburn  6674:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6675:         $setprivs = 1;
1.994     raeburn  6676:     }
1.1172.2.9  raeburn  6677:     return $setprivs;
1.994     raeburn  6678: }
                   6679: 
                   6680: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6681: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6682:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6683:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6684:     if ($sec ne '') {
                   6685:         $area .= '/'.$sec;
                   6686:     }
1.994     raeburn  6687:     my $spec = $role.'.'.$area;
                   6688:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6689:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6690:     my %rolehash = ();
1.1172.2.89  raeburn  6691:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6692:         my $rolename = $1;
1.1172.2.84  raeburn  6693:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6694:         my %domdef = &get_domain_defaults($dcdom);
                   6695:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6696:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6697:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6698:             }
                   6699:         }
1.1172.2.84  raeburn  6700:     } else {
                   6701:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6702:     }
1.1172.2.91  raeburn  6703:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6704:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6705:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6706:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6707:         &appenv( {'request.role'        => $spec,
                   6708:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6709:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6710:                  }
                   6711:                );
                   6712:         my $tadv=0;
                   6713:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6714:         &appenv({'request.role.adv'    => $tadv});
                   6715:     }
1.994     raeburn  6716: }
                   6717: 
1.12      www      6718: # --------------------------------------------------------------- get interface
                   6719: 
                   6720: sub get {
1.131     albertel 6721:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6722:    my $items='';
1.800     albertel 6723:    foreach my $item (@$storearr) {
                   6724:        $items.=&escape($item).'&';
1.191     harris41 6725:    }
1.12      www      6726:    $items=~s/\&$//;
1.620     albertel 6727:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6728:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6729:    my $uhome=&homeserver($uname,$udomain);
                   6730: 
1.133     albertel 6731:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6732:    my @pairs=split(/\&/,$rep);
1.273     albertel 6733:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6734:      return @pairs;
                   6735:    }
1.15      www      6736:    my %returnhash=();
1.42      www      6737:    my $i=0;
1.800     albertel 6738:    foreach my $item (@$storearr) {
                   6739:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6740:       $i++;
1.191     harris41 6741:    }
1.15      www      6742:    return %returnhash;
1.27      www      6743: }
                   6744: 
                   6745: # --------------------------------------------------------------- del interface
                   6746: 
                   6747: sub del {
1.133     albertel 6748:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6749:    my $items='';
1.800     albertel 6750:    foreach my $item (@$storearr) {
                   6751:        $items.=&escape($item).'&';
1.191     harris41 6752:    }
1.984     neumanie 6753: 
1.27      www      6754:    $items=~s/\&$//;
1.620     albertel 6755:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6756:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6757:    my $uhome=&homeserver($uname,$udomain);
                   6758:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6759: }
                   6760: 
                   6761: # -------------------------------------------------------------- dump interface
                   6762: 
1.1172.2.22  raeburn  6763: sub unserialize {
                   6764:     my ($rep, $escapedkeys) = @_;
                   6765: 
                   6766:     return {} if $rep =~ /^error/;
                   6767: 
                   6768:     my %returnhash=();
                   6769:     foreach my $item (split(/\&/,$rep)) {
                   6770:         my ($key, $value) = split(/=/, $item, 2);
                   6771:         $key = unescape($key) unless $escapedkeys;
                   6772:         next if $key =~ /^error: 2 /;
                   6773:         $returnhash{$key} = &thaw_unescape($value);
                   6774:     }
                   6775:     return \%returnhash;
                   6776: }
                   6777: 
                   6778: # see Lond::dump_with_regexp
                   6779: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6780: sub dump {
1.1172.2.22  raeburn  6781:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6782:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6783:     if (!$uname) { $uname=$env{'user.name'}; }
                   6784:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6785: 
1.1172.2.55  raeburn  6786:     if ($regexp) {
                   6787:         $regexp=&escape($regexp);
                   6788:     } else {
                   6789:         $regexp='.';
                   6790:     }
1.1172.2.22  raeburn  6791:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6792:         # user is hosted on this machine
1.1172.2.55  raeburn  6793:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6794:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6795:         return %{&unserialize($reply, $escapedkeys)};
                   6796:     }
1.1166    raeburn  6797:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6798:     my @pairs=split(/\&/,$rep);
                   6799:     my %returnhash=();
1.1098    foxr     6800:     if (!($rep =~ /^error/ )) {
                   6801: 	foreach my $item (@pairs) {
                   6802: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6803:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6804: 	    next if ($key =~ /^error: 2 /);
                   6805: 	    $returnhash{$key}=&thaw_unescape($value);
                   6806: 	}
1.755     albertel 6807:     }
                   6808:     return %returnhash;
1.407     www      6809: }
                   6810: 
1.1098    foxr     6811: 
1.717     albertel 6812: # --------------------------------------------------------- dumpstore interface
                   6813: 
                   6814: sub dumpstore {
                   6815:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6816:    # same as dump but keys must be escaped. They may contain colon separated
                   6817:    # lists of values that may themself contain colons (e.g. symbs).
                   6818:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6819: }
                   6820: 
1.407     www      6821: # -------------------------------------------------------------- keys interface
                   6822: 
                   6823: sub getkeys {
                   6824:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6825:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6826:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6827:    my $uhome=&homeserver($uname,$udomain);
                   6828:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6829:    my @keyarray=();
1.800     albertel 6830:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6831:       next if ($key =~ /^error: 2 /);
1.800     albertel 6832:       push(@keyarray,&unescape($key));
1.407     www      6833:    }
                   6834:    return @keyarray;
1.318     matthew  6835: }
                   6836: 
1.319     matthew  6837: # --------------------------------------------------------------- currentdump
                   6838: sub currentdump {
1.328     matthew  6839:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6840:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6841:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6842:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6843:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6844:    my $rep;
                   6845: 
                   6846:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6847:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6848:                    $courseid)));
                   6849:    } else {
                   6850:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6851:    }
                   6852: 
1.318     matthew  6853:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6854:    #
1.318     matthew  6855:    my %returnhash=();
1.319     matthew  6856:    #
1.1172.2.118.  .1(raebu 6857:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6858:        # an old lond will not know currentdump
                   6859:        # Do a dump and make it look like a currentdump
1.822     albertel 6860:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6861:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6862:        my %hash = @tmp;
                   6863:        @tmp=();
1.424     matthew  6864:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6865:    } else {
                   6866:        my @pairs=split(/\&/,$rep);
1.800     albertel 6867:        foreach my $pair (@pairs) {
                   6868:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6869:            my ($symb,$param) = split(/:/,$key);
                   6870:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6871:                                                         &thaw_unescape($value);
1.319     matthew  6872:        }
1.191     harris41 6873:    }
1.12      www      6874:    return %returnhash;
1.424     matthew  6875: }
                   6876: 
                   6877: sub convert_dump_to_currentdump{
                   6878:     my %hash = %{shift()};
                   6879:     my %returnhash;
                   6880:     # Code ripped from lond, essentially.  The only difference
                   6881:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6882:     # we might run in to problems with parameter names =~ /^v\./
                   6883:     while (my ($key,$value) = each(%hash)) {
                   6884:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6885: 	$symb  = &unescape($symb);
                   6886: 	$param = &unescape($param);
1.424     matthew  6887:         next if ($v eq 'version' || $symb eq 'keys');
                   6888:         next if (exists($returnhash{$symb}) &&
                   6889:                  exists($returnhash{$symb}->{$param}) &&
                   6890:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6891:         $returnhash{$symb}->{$param}=$value;
                   6892:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6893:     }
                   6894:     #
                   6895:     # Remove all of the keys in the hashes which keep track of
                   6896:     # the version of the parameter.
                   6897:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6898:         # use a foreach because we are going to delete from the hash.
                   6899:         foreach my $key (keys(%$param_hash)) {
                   6900:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6901:         }
                   6902:     }
                   6903:     return \%returnhash;
1.12      www      6904: }
                   6905: 
1.627     albertel 6906: # ------------------------------------------------------ critical inc interface
                   6907: 
                   6908: sub cinc {
                   6909:     return &inc(@_,'critical');
                   6910: }
                   6911: 
1.449     matthew  6912: # --------------------------------------------------------------- inc interface
                   6913: 
                   6914: sub inc {
1.627     albertel 6915:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6916:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6917:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6918:     my $uhome=&homeserver($uname,$udomain);
                   6919:     my $items='';
                   6920:     if (! ref($store)) {
                   6921:         # got a single value, so use that instead
                   6922:         $items = &escape($store).'=&';
                   6923:     } elsif (ref($store) eq 'SCALAR') {
                   6924:         $items = &escape($$store).'=&';        
                   6925:     } elsif (ref($store) eq 'ARRAY') {
                   6926:         $items = join('=&',map {&escape($_);} @{$store});
                   6927:     } elsif (ref($store) eq 'HASH') {
                   6928:         while (my($key,$value) = each(%{$store})) {
                   6929:             $items.= &escape($key).'='.&escape($value).'&';
                   6930:         }
                   6931:     }
                   6932:     $items=~s/\&$//;
1.627     albertel 6933:     if ($critical) {
                   6934: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6935:     } else {
                   6936: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6937:     }
1.449     matthew  6938: }
                   6939: 
1.12      www      6940: # --------------------------------------------------------------- put interface
                   6941: 
                   6942: sub put {
1.134     albertel 6943:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6944:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6945:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6946:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6947:    my $items='';
1.800     albertel 6948:    foreach my $item (keys(%$storehash)) {
                   6949:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6950:    }
1.12      www      6951:    $items=~s/\&$//;
1.134     albertel 6952:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6953: }
                   6954: 
1.631     albertel 6955: # ------------------------------------------------------------ newput interface
                   6956: 
                   6957: sub newput {
                   6958:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6959:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6960:    if (!$uname) { $uname=$env{'user.name'}; }
                   6961:    my $uhome=&homeserver($uname,$udomain);
                   6962:    my $items='';
                   6963:    foreach my $key (keys(%$storehash)) {
                   6964:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6965:    }
                   6966:    $items=~s/\&$//;
                   6967:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6968: }
                   6969: 
                   6970: # ---------------------------------------------------------  putstore interface
                   6971: 
1.524     raeburn  6972: sub putstore {
1.1172.2.59  raeburn  6973:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6975:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6976:    my $uhome=&homeserver($uname,$udomain);
                   6977:    my $items='';
1.715     albertel 6978:    foreach my $key (keys(%$storehash)) {
                   6979:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6980:    }
1.715     albertel 6981:    $items=~s/\&$//;
1.716     albertel 6982:    my $esc_symb=&escape($symb);
                   6983:    my $esc_v=&escape($version);
1.715     albertel 6984:    my $reply =
1.716     albertel 6985:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6986: 	      $uhome);
1.1172.2.59  raeburn  6987:    if (($tolog) && ($reply eq 'ok')) {
                   6988:        my $namevalue='';
                   6989:        foreach my $key (keys(%{$storehash})) {
                   6990:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6991:        }
                   6992:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6993:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6994:                      '&version='.$esc_v.
                   6995:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6996:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6997:    }
1.715     albertel 6998:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6999:        # gfall back to way things use to be done
1.715     albertel 7000:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7001: 			    $uname);
1.524     raeburn  7002:    }
1.715     albertel 7003:    return $reply;
                   7004: }
                   7005: 
                   7006: sub old_putstore {
1.716     albertel 7007:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7008:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7009:     if (!$uname) { $uname=$env{'user.name'}; }
                   7010:     my $uhome=&homeserver($uname,$udomain);
                   7011:     my %newstorehash;
1.800     albertel 7012:     foreach my $item (keys(%$storehash)) {
                   7013: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7014: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7015:     }
                   7016:     my $items='';
                   7017:     my %allitems = ();
1.800     albertel 7018:     foreach my $item (keys(%newstorehash)) {
                   7019: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7020: 	    my $key = $1.':keys:'.$2;
                   7021: 	    $allitems{$key} .= $3.':';
                   7022: 	}
1.800     albertel 7023: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7024:     }
1.800     albertel 7025:     foreach my $item (keys(%allitems)) {
                   7026: 	$allitems{$item} =~ s/\:$//;
                   7027: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7028:     }
                   7029:     $items=~s/\&$//;
                   7030:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7031: }
                   7032: 
1.47      www      7033: # ------------------------------------------------------ critical put interface
                   7034: 
                   7035: sub cput {
1.134     albertel 7036:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7037:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7038:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7039:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7040:    my $items='';
1.800     albertel 7041:    foreach my $item (keys(%$storehash)) {
                   7042:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7043:    }
1.47      www      7044:    $items=~s/\&$//;
1.134     albertel 7045:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7046: }
                   7047: 
                   7048: # -------------------------------------------------------------- eget interface
                   7049: 
                   7050: sub eget {
1.133     albertel 7051:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7052:    my $items='';
1.800     albertel 7053:    foreach my $item (@$storearr) {
                   7054:        $items.=&escape($item).'&';
1.191     harris41 7055:    }
1.12      www      7056:    $items=~s/\&$//;
1.620     albertel 7057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7058:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7059:    my $uhome=&homeserver($uname,$udomain);
                   7060:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7061:    my @pairs=split(/\&/,$rep);
                   7062:    my %returnhash=();
1.42      www      7063:    my $i=0;
1.800     albertel 7064:    foreach my $item (@$storearr) {
                   7065:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7066:       $i++;
1.191     harris41 7067:    }
1.12      www      7068:    return %returnhash;
                   7069: }
                   7070: 
1.667     albertel 7071: # ------------------------------------------------------------ tmpput interface
                   7072: sub tmpput {
1.802     raeburn  7073:     my ($storehash,$server,$context)=@_;
1.667     albertel 7074:     my $items='';
1.800     albertel 7075:     foreach my $item (keys(%$storehash)) {
                   7076: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7077:     }
                   7078:     $items=~s/\&$//;
1.802     raeburn  7079:     if (defined($context)) {
                   7080:         $items .= ':'.&escape($context);
                   7081:     }
1.667     albertel 7082:     return &reply("tmpput:$items",$server);
                   7083: }
                   7084: 
                   7085: # ------------------------------------------------------------ tmpget interface
                   7086: sub tmpget {
1.688     albertel 7087:     my ($token,$server)=@_;
                   7088:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7089:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7090:     my %returnhash;
1.1172.2.85  raeburn  7091:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7092:         return %returnhash;
                   7093:     }
1.667     albertel 7094:     foreach my $item (split(/\&/,$rep)) {
                   7095: 	my ($key,$value)=split(/=/,$item);
                   7096: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7097:     }
                   7098:     return %returnhash;
                   7099: }
                   7100: 
1.1113    raeburn  7101: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7102: sub tmpdel {
                   7103:     my ($token,$server)=@_;
                   7104:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7105:     return &reply("tmpdel:$token",$server);
                   7106: }
                   7107: 
1.1172.2.13  raeburn  7108: # ------------------------------------------------------------ get_timebased_id
                   7109: 
                   7110: sub get_timebased_id {
                   7111:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7112:         $maxtries) = @_;
                   7113:     my ($newid,$error,$dellock);
                   7114:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7115:         return ('','ok','invalid call to get suffix');
                   7116:     }
                   7117: 
                   7118: # set defaults for any optional args for which values were not supplied
                   7119:     if ($who eq '') {
                   7120:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7121:     }
                   7122:     if (!$locktries) {
                   7123:         $locktries = 3;
                   7124:     }
                   7125:     if (!$maxtries) {
                   7126:         $maxtries = 10;
                   7127:     }
                   7128: 
                   7129:     if (($cdom eq '') || ($cnum eq '')) {
                   7130:         if ($env{'request.course.id'}) {
                   7131:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7132:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7133:         }
                   7134:         if (($cdom eq '') || ($cnum eq '')) {
                   7135:             return ('','ok','call to get suffix not in course context');
                   7136:         }
                   7137:     }
                   7138: 
                   7139: # construct locking item
                   7140:     my $lockhash = {
                   7141:                       $prefix."\0".'locked_'.$keyid => $who,
                   7142:                    };
                   7143:     my $tries = 0;
                   7144: 
                   7145: # attempt to get lock on nohist_$namespace file
                   7146:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7147:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7148:         $tries ++;
                   7149:         sleep 1;
                   7150:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7151:     }
                   7152: 
                   7153: # attempt to get unique identifier, based on current timestamp
                   7154:     if ($gotlock eq 'ok') {
                   7155:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7156:         my $id = time;
                   7157:         $newid = $id;
1.1172.2.56  raeburn  7158:         if ($idtype eq 'addcode') {
                   7159:             $newid .= &sixnum_code();
                   7160:         }
1.1172.2.13  raeburn  7161:         my $idtries = 0;
                   7162:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7163:             if ($idtype eq 'concat') {
                   7164:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7165:             } elsif ($idtype eq 'addcode') {
                   7166:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7167:             } else {
                   7168:                 $newid ++;
                   7169:             }
                   7170:             $idtries ++;
                   7171:         }
                   7172:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7173:             my %new_item =  (
                   7174:                               $prefix."\0".$newid => $who,
                   7175:                             );
                   7176:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7177:                                                  $cdom,$cnum);
                   7178:             if ($putresult ne 'ok') {
                   7179:                 undef($newid);
                   7180:                 $error = 'error saving new item: '.$putresult;
                   7181:             }
                   7182:         } else {
1.1172.2.56  raeburn  7183:              undef($newid);
1.1172.2.13  raeburn  7184:              $error = ('error: no unique suffix available for the new item ');
                   7185:         }
                   7186: #  remove lock
                   7187:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7188:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7189:     } else {
                   7190:         $error = "error: could not obtain lockfile\n";
                   7191:         $dellock = 'ok';
1.1172.2.58  raeburn  7192:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7193:             $dellock = 'nolock';
                   7194:         }
1.1172.2.13  raeburn  7195:     }
                   7196:     return ($newid,$dellock,$error);
                   7197: }
                   7198: 
1.1172.2.56  raeburn  7199: sub sixnum_code {
                   7200:     my $code;
                   7201:     for (0..6) {
                   7202:         $code .= int( rand(9) );
                   7203:     }
                   7204:     return $code;
                   7205: }
                   7206: 
1.765     albertel 7207: # -------------------------------------------------- portfolio access checking
                   7208: 
                   7209: sub portfolio_access {
1.1172.2.77  raeburn  7210:     my ($requrl,$clientip) = @_;
1.765     albertel 7211:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7212:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7213:     if ($result) {
                   7214:         my %setters;
                   7215:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7216:             my ($startblock,$endblock) =
                   7217:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7218:             if ($startblock && $endblock) {
                   7219:                 return 'B';
                   7220:             }
                   7221:         } else {
                   7222:             my ($startblock,$endblock) =
                   7223:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7224:             if ($startblock && $endblock) {
                   7225:                 return 'B';
                   7226:             }
                   7227:         }
                   7228:     }
1.765     albertel 7229:     if ($result eq 'ok') {
1.766     albertel 7230:        return 'F';
1.765     albertel 7231:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7232:        return 'A';
1.765     albertel 7233:     }
1.766     albertel 7234:     return '';
1.765     albertel 7235: }
                   7236: 
                   7237: sub get_portfolio_access {
1.1172.2.77  raeburn  7238:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7239: 
                   7240:     if (!ref($access_hash)) {
                   7241: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7242: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7243: 						   $file_name);
                   7244: 	$access_hash = $access_controls{$file_name};
                   7245:     }
                   7246: 
1.1172.2.77  raeburn  7247:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7248:     my $now = time;
                   7249:     if (ref($access_hash) eq 'HASH') {
                   7250:         foreach my $key (keys(%{$access_hash})) {
                   7251:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7252:             if ($start > $now) {
                   7253:                 next;
                   7254:             }
                   7255:             if ($end && $end<$now) {
                   7256:                 next;
                   7257:             }
                   7258:             if ($scope eq 'public') {
                   7259:                 $public = $key;
                   7260:                 last;
                   7261:             } elsif ($scope eq 'guest') {
                   7262:                 $guest = $key;
                   7263:             } elsif ($scope eq 'domains') {
                   7264:                 push(@domains,$key);
                   7265:             } elsif ($scope eq 'users') {
                   7266:                 push(@users,$key);
                   7267:             } elsif ($scope eq 'course') {
                   7268:                 push(@courses,$key);
                   7269:             } elsif ($scope eq 'group') {
                   7270:                 push(@groups,$key);
1.1172.2.77  raeburn  7271:             } elsif ($scope eq 'ip') {
                   7272:                 push(@ips,$key);
1.765     albertel 7273:             }
                   7274:         }
                   7275:         if ($public) {
                   7276:             return 'ok';
1.1172.2.77  raeburn  7277:         } elsif (@ips > 0) {
                   7278:             my $allowed;
                   7279:             foreach my $ipkey (@ips) {
                   7280:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7281:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7282:                         $allowed = 1;
                   7283:                         last;
                   7284:                     }
                   7285:                 }
                   7286:             }
                   7287:             if ($allowed) {
                   7288:                 return 'ok';
                   7289:             }
1.765     albertel 7290:         }
                   7291:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7292:             if ($guest) {
                   7293:                 return $guest;
                   7294:             }
                   7295:         } else {
                   7296:             if (@domains > 0) {
                   7297:                 foreach my $domkey (@domains) {
                   7298:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7299:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7300:                             return 'ok';
                   7301:                         }
                   7302:                     }
                   7303:                 }
                   7304:             }
                   7305:             if (@users > 0) {
                   7306:                 foreach my $userkey (@users) {
1.865     raeburn  7307:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7308:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7309:                             if (ref($item) eq 'HASH') {
                   7310:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7311:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7312:                                     return 'ok';
                   7313:                                 }
                   7314:                             }
                   7315:                         }
                   7316:                     } 
1.765     albertel 7317:                 }
                   7318:             }
                   7319:             my %roleshash;
                   7320:             my @courses_and_groups = @courses;
                   7321:             push(@courses_and_groups,@groups); 
                   7322:             if (@courses_and_groups > 0) {
                   7323:                 my (%allgroups,%allroles); 
                   7324:                 my ($start,$end,$role,$sec,$group);
                   7325:                 foreach my $envkey (%env) {
1.1060    raeburn  7326:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7327:                         my $cid = $2.'_'.$3; 
                   7328:                         if ($1 eq 'gr') {
                   7329:                             $group = $4;
                   7330:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7331:                         } else {
                   7332:                             if ($4 eq '') {
                   7333:                                 $sec = 'none';
                   7334:                             } else {
                   7335:                                 $sec = $4;
                   7336:                             }
                   7337:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7338:                         }
1.811     albertel 7339:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7340:                         my $cid = $2.'_'.$3;
                   7341:                         if ($4 eq '') {
                   7342:                             $sec = 'none';
                   7343:                         } else {
                   7344:                             $sec = $4;
                   7345:                         }
                   7346:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7347:                     }
                   7348:                 }
                   7349:                 if (keys(%allroles) == 0) {
                   7350:                     return;
                   7351:                 }
                   7352:                 foreach my $key (@courses_and_groups) {
                   7353:                     my %content = %{$$access_hash{$key}};
                   7354:                     my $cnum = $content{'number'};
                   7355:                     my $cdom = $content{'domain'};
                   7356:                     my $cid = $cdom.'_'.$cnum;
                   7357:                     if (!exists($allroles{$cid})) {
                   7358:                         next;
                   7359:                     }    
                   7360:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7361:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7362:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7363:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7364:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7365:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7366:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7367:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7368:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7369:                                         if (grep/^all$/,@sections) {
                   7370:                                             return 'ok';
                   7371:                                         } else {
                   7372:                                             if (grep/^$sec$/,@sections) {
                   7373:                                                 return 'ok';
                   7374:                                             }
                   7375:                                         }
                   7376:                                     }
                   7377:                                 }
                   7378:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7379:                                     if (grep/^none$/,@groups) {
                   7380:                                         return 'ok';
                   7381:                                     }
                   7382:                                 } else {
                   7383:                                     if (grep/^all$/,@groups) {
                   7384:                                         return 'ok';
                   7385:                                     } 
                   7386:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7387:                                         if (grep/^$group$/,@groups) {
                   7388:                                             return 'ok';
                   7389:                                         }
                   7390:                                     }
                   7391:                                 } 
                   7392:                             }
                   7393:                         }
                   7394:                     }
                   7395:                 }
                   7396:             }
                   7397:             if ($guest) {
                   7398:                 return $guest;
                   7399:             }
                   7400:         }
                   7401:     }
                   7402:     return;
                   7403: }
                   7404: 
                   7405: sub course_group_datechecker {
                   7406:     my ($dates,$now,$status) = @_;
                   7407:     my ($start,$end) = split(/\./,$dates);
                   7408:     if (!$start && !$end) {
                   7409:         return 'ok';
                   7410:     }
                   7411:     if (grep/^active$/,@{$status}) {
                   7412:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7413:             return 'ok';
                   7414:         }
                   7415:     }
                   7416:     if (grep/^previous$/,@{$status}) {
                   7417:         if ($end > $now ) {
                   7418:             return 'ok';
                   7419:         }
                   7420:     }
                   7421:     if (grep/^future$/,@{$status}) {
                   7422:         if ($start > $now) {
                   7423:             return 'ok';
                   7424:         }
                   7425:     }
                   7426:     return; 
                   7427: }
                   7428: 
                   7429: sub parse_portfolio_url {
                   7430:     my ($url) = @_;
                   7431: 
                   7432:     my ($type,$udom,$unum,$group,$file_name);
                   7433:     
1.823     albertel 7434:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7435: 	$type = 1;
                   7436:         $udom = $1;
                   7437:         $unum = $2;
                   7438:         $file_name = $3;
1.823     albertel 7439:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7440: 	$type = 2;
                   7441:         $udom = $1;
                   7442:         $unum = $2;
                   7443:         $group = $3;
                   7444:         $file_name = $3.'/'.$4;
                   7445:     }
                   7446:     if (wantarray) {
                   7447: 	return ($type,$udom,$unum,$file_name,$group);
                   7448:     }
                   7449:     return $type;
                   7450: }
                   7451: 
                   7452: sub is_portfolio_url {
                   7453:     my ($url) = @_;
                   7454:     return scalar(&parse_portfolio_url($url));
                   7455: }
                   7456: 
1.798     raeburn  7457: sub is_portfolio_file {
                   7458:     my ($file) = @_;
1.820     raeburn  7459:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7460:         return 1;
                   7461:     }
                   7462:     return;
                   7463: }
                   7464: 
1.976     raeburn  7465: sub usertools_access {
1.1084    raeburn  7466:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7467:     my ($access,%tools);
                   7468:     if ($context eq '') {
                   7469:         $context = 'tools';
                   7470:     }
                   7471:     if ($context eq 'requestcourses') {
                   7472:         %tools = (
                   7473:                       official   => 1,
                   7474:                       unofficial => 1,
1.1006    raeburn  7475:                       community  => 1,
1.1172.2.37  raeburn  7476:                       textbook   => 1,
1.985     raeburn  7477:                  );
1.1172.2.9  raeburn  7478:     } elsif ($context eq 'requestauthor') {
                   7479:         %tools = (
                   7480:                       requestauthor => 1,
                   7481:                  );
1.985     raeburn  7482:     } else {
                   7483:         %tools = (
                   7484:                       aboutme   => 1,
                   7485:                       blog      => 1,
1.1172.2.6  raeburn  7486:                       webdav    => 1,
1.985     raeburn  7487:                       portfolio => 1,
                   7488:                  );
                   7489:     }
1.976     raeburn  7490:     return if (!defined($tools{$tool}));
                   7491: 
1.1172.2.35  raeburn  7492:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7493:         $udom = $env{'user.domain'};
                   7494:         $uname = $env{'user.name'};
                   7495:     }
                   7496: 
1.978     raeburn  7497:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7498:         if ($action ne 'reload') {
1.985     raeburn  7499:             if ($context eq 'requestcourses') {
                   7500:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7501:             } elsif ($context eq 'requestauthor') {
                   7502:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7503:             } else {
                   7504:                 return $env{'environment.availabletools.'.$tool};
                   7505:             }
                   7506:         }
1.976     raeburn  7507:     }
                   7508: 
1.1172.2.9  raeburn  7509:     my ($toolstatus,$inststatus,$envkey);
                   7510:     if ($context eq 'requestauthor') {
                   7511:         $envkey = $context;
                   7512:     } else {
                   7513:         $envkey = $context.'.'.$tool;
                   7514:     }
1.976     raeburn  7515: 
1.985     raeburn  7516:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7517:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7518:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7519:         $inststatus = $env{'environment.inststatus'};
                   7520:     } else {
1.1084    raeburn  7521:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7522:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7523:             $inststatus = $userenvref->{'inststatus'};
                   7524:         } else {
1.1172.2.9  raeburn  7525:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7526:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7527:             $inststatus = $userenv{'inststatus'};
                   7528:         }
1.976     raeburn  7529:     }
                   7530: 
                   7531:     if ($toolstatus ne '') {
                   7532:         if ($toolstatus) {
                   7533:             $access = 1;
                   7534:         } else {
                   7535:             $access = 0;
                   7536:         }
                   7537:         return $access;
                   7538:     }
                   7539: 
1.1084    raeburn  7540:     my ($is_adv,%domdef);
                   7541:     if (ref($is_advref) eq 'HASH') {
                   7542:         $is_adv = $is_advref->{'is_adv'};
                   7543:     } else {
                   7544:         $is_adv = &is_advanced_user($udom,$uname);
                   7545:     }
                   7546:     if (ref($domdefref) eq 'HASH') {
                   7547:         %domdef = %{$domdefref};
                   7548:     } else {
                   7549:         %domdef = &get_domain_defaults($udom);
                   7550:     }
1.976     raeburn  7551:     if (ref($domdef{$tool}) eq 'HASH') {
                   7552:         if ($is_adv) {
                   7553:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7554:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7555:                     $access = 1;
                   7556:                 } else {
                   7557:                     $access = 0;
                   7558:                 }
                   7559:                 return $access;
                   7560:             }
                   7561:         }
                   7562:         if ($inststatus ne '') {
                   7563:             my ($hasaccess,$hasnoaccess);
                   7564:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7565:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7566:                     if ($domdef{$tool}{$affiliation}) {
                   7567:                         $hasaccess = 1;
                   7568:                     } else {
                   7569:                         $hasnoaccess = 1;
                   7570:                     }
                   7571:                 }
                   7572:             }
                   7573:             if ($hasaccess || $hasnoaccess) {
                   7574:                 if ($hasaccess) {
                   7575:                     $access = 1;
                   7576:                 } elsif ($hasnoaccess) {
                   7577:                     $access = 0; 
                   7578:                 }
                   7579:                 return $access;
                   7580:             }
                   7581:         } else {
                   7582:             if ($domdef{$tool}{'default'} ne '') {
                   7583:                 if ($domdef{$tool}{'default'}) {
                   7584:                     $access = 1;
                   7585:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7586:                     $access = 0;
                   7587:                 }
                   7588:                 return $access;
                   7589:             }
                   7590:         }
                   7591:     } else {
1.1172.2.6  raeburn  7592:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7593:             $access = 1;
                   7594:         } else {
                   7595:             $access = 0;
                   7596:         }
1.976     raeburn  7597:         return $access;
                   7598:     }
                   7599: }
                   7600: 
1.1050    raeburn  7601: sub is_course_owner {
                   7602:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7603:     if (($udom eq '') || ($uname eq '')) {
                   7604:         $udom = $env{'user.domain'};
                   7605:         $uname = $env{'user.name'};
                   7606:     }
                   7607:     unless (($udom eq '') || ($uname eq '')) {
                   7608:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7609:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7610:                 return 1;
                   7611:             } else {
                   7612:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7613:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7614:                     return 1;
                   7615:                 }
                   7616:             }
                   7617:         }
                   7618:     }
                   7619:     return;
                   7620: }
                   7621: 
1.976     raeburn  7622: sub is_advanced_user {
                   7623:     my ($udom,$uname) = @_;
1.1085    raeburn  7624:     if ($udom ne '' && $uname ne '') {
                   7625:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7626:             if (wantarray) {
                   7627:                 return ($env{'user.adv'},$env{'user.author'});
                   7628:             } else {
                   7629:                 return $env{'user.adv'};
                   7630:             }
1.1085    raeburn  7631:         }
                   7632:     }
1.976     raeburn  7633:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7634:     my %allroles;
1.1128    raeburn  7635:     my ($is_adv,$is_author);
1.976     raeburn  7636:     foreach my $role (keys(%roleshash)) {
                   7637:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7638:         my $area = '/'.$tdomain.'/'.$trest;
                   7639:         if ($sec ne '') {
                   7640:             $area .= '/'.$sec;
                   7641:         }
                   7642:         if (($area ne '') && ($trole ne '')) {
                   7643:             my $spec=$trole.'.'.$area;
                   7644:             if ($trole =~ /^cr\//) {
                   7645:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7646:             } elsif ($trole ne 'gr') {
                   7647:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7648:             }
1.1128    raeburn  7649:             if ($trole eq 'au') {
                   7650:                 $is_author = 1;
                   7651:             }
1.976     raeburn  7652:         }
                   7653:     }
                   7654:     foreach my $role (keys(%allroles)) {
                   7655:         last if ($is_adv);
                   7656:         foreach my $item (split(/:/,$allroles{$role})) {
                   7657:             if ($item ne '') {
                   7658:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7659:                 if ($privilege eq 'adv') {
                   7660:                     $is_adv = 1;
                   7661:                     last;
                   7662:                 }
                   7663:             }
                   7664:         }
                   7665:     }
1.1128    raeburn  7666:     if (wantarray) {
                   7667:         return ($is_adv,$is_author);
                   7668:     }
1.976     raeburn  7669:     return $is_adv;
                   7670: }
1.798     raeburn  7671: 
1.1035    raeburn  7672: sub check_can_request {
1.1036    raeburn  7673:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7674:     my $canreq = 0;
                   7675:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7676:     my @options = ('approval','validate','autolimit');
                   7677:     my $optregex = join('|',@options);
                   7678:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7679:         foreach my $type (@{$types}) {
                   7680:             if (&usertools_access($env{'user.name'},
                   7681:                                   $env{'user.domain'},
                   7682:                                   $type,undef,'requestcourses')) {
                   7683:                 $canreq ++;
1.1036    raeburn  7684:                 if (ref($request_domains) eq 'HASH') {
                   7685:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7686:                 }
1.1035    raeburn  7687:                 if ($dom eq $env{'user.domain'}) {
                   7688:                     $can_request->{$type} = 1;
                   7689:                 }
                   7690:             }
                   7691:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7692:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7693:                 if (@curr > 0) {
1.1036    raeburn  7694:                     foreach my $item (@curr) {
                   7695:                         if (ref($request_domains) eq 'HASH') {
                   7696:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7697:                             if ($otherdom ne '') {
                   7698:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7699:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7700:                                         push(@{$request_domains->{$type}},$otherdom);
                   7701:                                     }
                   7702:                                 } else {
                   7703:                                     push(@{$request_domains->{$type}},$otherdom);
                   7704:                                 }
                   7705:                             }
                   7706:                         }
                   7707:                     }
                   7708:                     unless($dom eq $env{'user.domain'}) {
                   7709:                         $canreq ++;
1.1035    raeburn  7710:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7711:                             $can_request->{$type} = 1;
                   7712:                         }
                   7713:                     }
                   7714:                 }
                   7715:             }
                   7716:         }
                   7717:     }
                   7718:     return $canreq;
                   7719: }
                   7720: 
1.341     www      7721: # ---------------------------------------------- Custom access rule evaluation
                   7722: 
                   7723: sub customaccess {
                   7724:     my ($priv,$uri)=@_;
1.807     albertel 7725:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7726:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7727:     $udom = &LONCAPA::clean_domain($udom);
                   7728:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7729:     my $access=0;
1.800     albertel 7730:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7731: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7732: 	if ($type eq 'user') {
                   7733: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7734: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7735: 		if ($tdom) {
                   7736: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7737: 		}
1.896     albertel 7738: 		if ($tuname) {
                   7739: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7740: 		}
                   7741: 		$access=($effect eq 'allow');
                   7742: 		last;
                   7743: 	    }
                   7744: 	} else {
                   7745: 	    if ($role) {
                   7746: 		if ($role ne $urole) { next; }
                   7747: 	    }
                   7748: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7749: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7750: 		if ($tdom) {
                   7751: 		    if ($tdom ne $udom) { next; }
                   7752: 		}
                   7753: 		if ($tcrs) {
                   7754: 		    if ($tcrs ne $ucrs) { next; }
                   7755: 		}
                   7756: 		if ($tsec) {
                   7757: 		    if ($tsec ne $usec) { next; }
                   7758: 		}
                   7759: 		$access=($effect eq 'allow');
                   7760: 		last;
                   7761: 	    }
                   7762: 	    if ($realm eq '' && $role eq '') {
                   7763: 		$access=($effect eq 'allow');
                   7764: 	    }
1.402     bowersj2 7765: 	}
1.341     www      7766:     }
                   7767:     return $access;
                   7768: }
                   7769: 
1.103     harris41 7770: # ------------------------------------------------- Check for a user privilege
1.12      www      7771: 
                   7772: sub allowed {
1.1172.2.65  raeburn  7773:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7774:     my $ver_orguri=$uri;
1.439     www      7775:     $uri=&deversion($uri);
1.152     www      7776:     my $orguri=$uri;
1.52      www      7777:     $uri=&declutter($uri);
1.809     raeburn  7778: 
1.810     raeburn  7779:     if ($priv eq 'evb') {
                   7780: # Evade communication block restrictions for specified role in a course
                   7781:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7782:             return $1;
                   7783:         } else {
                   7784:             return;
                   7785:         }
                   7786:     }
                   7787: 
1.620     albertel 7788:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7789: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7790:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7791: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7792: 	&& ($priv eq 'bre')) {
1.14      www      7793: 	return 'F';
1.159     www      7794:     }
                   7795: 
1.545     banghart 7796: # Free bre access to user's own portfolio contents
1.714     raeburn  7797:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7798:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7799: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7800:         my %setters;
                   7801:         my ($startblock,$endblock) = 
                   7802:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7803:         if ($startblock && $endblock) {
                   7804:             return 'B';
                   7805:         } else {
                   7806:             return 'F';
                   7807:         }
1.545     banghart 7808:     }
                   7809: 
1.762     raeburn  7810: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7811:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7812:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7813:         if (exists($env{'request.course.id'})) {
                   7814:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7815:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7816:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7817:                 my $courseprivid=$env{'request.course.id'};
                   7818:                 $courseprivid=~s/\_/\//;
                   7819:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7820:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7821:                     return $1; 
1.762     raeburn  7822:                 } else {
                   7823:                     if ($env{'request.course.sec'}) {
                   7824:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7825:                     }
                   7826:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7827:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7828:                         return $2;
                   7829:                     }
1.714     raeburn  7830:                 }
                   7831:             }
                   7832:         }
                   7833:     }
                   7834: 
1.159     www      7835: # Free bre to public access
                   7836: 
                   7837:     if ($priv eq 'bre') {
1.238     www      7838:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7839: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7840:            return 'F'; 
                   7841:         }
1.238     www      7842:         if ($copyright eq 'priv') {
                   7843:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7844: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7845: 		return '';
                   7846:             }
                   7847:         }
                   7848:         if ($copyright eq 'domain') {
                   7849:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7850: 	    unless (($env{'user.domain'} eq $1) ||
                   7851:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7852: 		return '';
                   7853:             }
1.262     matthew  7854:         }
1.620     albertel 7855:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7856:             # Library role, so allow browsing of resources in this domain.
                   7857:             return 'F';
1.238     www      7858:         }
1.341     www      7859:         if ($copyright eq 'custom') {
                   7860: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7861:         }
1.14      www      7862:     }
1.264     matthew  7863:     # Domain coordinator is trying to create a course
1.620     albertel 7864:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7865:         # uri is the requested domain in this case.
                   7866:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7867:         # a role of dc for the domain in question.
1.620     albertel 7868:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7869:     }
1.29      www      7870: 
1.52      www      7871:     my $thisallowed='';
                   7872:     my $statecond=0;
                   7873:     my $courseprivid='';
                   7874: 
1.1039    raeburn  7875:     my $ownaccess;
1.1043    raeburn  7876:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7877:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7878:         if ($uri eq '') {
                   7879:             $ownaccess = 1;
                   7880:         } else {
                   7881:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7882:                 my $udom = $env{'user.domain'};
                   7883:                 my $uname = $env{'user.name'};
                   7884:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7885:                     $ownaccess = 1;
1.1040    raeburn  7886:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7887:                     unless ($uri =~ m{\.\./}) {
                   7888:                         $ownaccess = 1;
                   7889:                     }
                   7890:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7891:                     my $now = time;
                   7892:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7893:                         my $adom = $1;
                   7894:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7895:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7896:                                 my ($start,$end) = split('.',$env{$key});
                   7897:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7898:                                     $ownaccess = 1;
                   7899:                                     last;
                   7900:                                 }
                   7901:                             }
                   7902:                         }
                   7903:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7904:                         my $adom = $1;
                   7905:                         my $aname = $2;
1.1042    raeburn  7906:                         foreach my $role ('ca','aa') { 
                   7907:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7908:                                 my ($start,$end) =
                   7909:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7910:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7911:                                     $ownaccess = 1;
                   7912:                                     last;
                   7913:                                 }
1.1039    raeburn  7914:                             }
                   7915:                         }
                   7916:                     }
                   7917:                 }
                   7918:             }
                   7919:         }
                   7920:     }
                   7921: 
1.52      www      7922: # Course
                   7923: 
1.620     albertel 7924:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7925:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7926:             $thisallowed.=$1;
                   7927:         }
1.52      www      7928:     }
1.29      www      7929: 
1.52      www      7930: # Domain
                   7931: 
1.620     albertel 7932:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7933:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7934:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7935:             $thisallowed.=$1;
                   7936:         }
1.12      www      7937:     }
1.52      www      7938: 
1.1141    raeburn  7939: # User who is not author or co-author might still be able to edit
                   7940: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7941:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7942:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7943:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7944:             $thisallowed.=$1;
                   7945:         }
                   7946:     }
                   7947: 
1.52      www      7948: # Course: uri itself is a course
1.66      www      7949:     my $courseuri=$uri;
                   7950:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7951:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7952: 
1.620     albertel 7953:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7954:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  7955:         if ($priv eq 'mip') {
                   7956:             my $rem = $1;
                   7957:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   7958:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   7959:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7960:                 if ($cdom ne '') {
                   7961:                     my %passwdconf = &get_passwdconf($cdom);
                   7962:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   7963:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   7964:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   7965:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   7966:                                 unless (@inststatuses) {
                   7967:                                     @inststatuses = ('default');
                   7968:                                 }
                   7969:                                 foreach my $status (@inststatuses) {
                   7970:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   7971:                                         $thisallowed.=$rem;
                   7972:                                     }
                   7973:                                 }
                   7974:                             }
                   7975:                         }
                   7976:                     }
                   7977:                 }
                   7978:             }
                   7979:         } else {
                   7980:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   7981:                 $thisallowed.=$1;
                   7982:             }
1.1039    raeburn  7983:         }
1.12      www      7984:     }
1.29      www      7985: 
1.665     albertel 7986: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7987: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7988:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7989: 	$thisallowed='';
1.671     raeburn  7990:         my ($match)=&is_on_map($uri);
                   7991:         if ($match) {
                   7992:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7993:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7994:                 my $value = $1;
                   7995:                 if ($noblockcheck) {
                   7996:                     $thisallowed.=$value;
1.1162    raeburn  7997:                 } else {
1.1172.2.65  raeburn  7998:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7999:                     if (@blockers > 0) {
                   8000:                         $thisallowed = 'B';
                   8001:                     } else {
                   8002:                         $thisallowed.=$value;
                   8003:                     }
1.1162    raeburn  8004:                 }
1.671     raeburn  8005:             }
                   8006:         } else {
1.705     albertel 8007:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8008:             if ($refuri) {
                   8009:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8010:                     $thisallowed='F';
1.671     raeburn  8011:                 } else {
                   8012:                     $refuri=&declutter($refuri);
                   8013:                     my ($match) = &is_on_map($refuri);
                   8014:                     if ($match) {
1.1172.2.65  raeburn  8015:                         if ($noblockcheck) {
1.1162    raeburn  8016:                             $thisallowed='F';
1.1172.2.65  raeburn  8017:                         } else {
                   8018:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8019:                             if (@blockers > 0) {
                   8020:                                 $thisallowed = 'B';
                   8021:                             } else {
                   8022:                                 $thisallowed='F';
                   8023:                             }
1.1162    raeburn  8024:                         }
1.671     raeburn  8025:                     }
1.669     raeburn  8026:                 }
1.671     raeburn  8027:             }
                   8028:         }
1.314     www      8029:     }
1.492     albertel 8030: 
1.766     albertel 8031:     if ($priv eq 'bre'
                   8032: 	&& $thisallowed ne 'F' 
                   8033: 	&& $thisallowed ne '2'
                   8034: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8035: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8036:     }
                   8037:     
1.52      www      8038: # Full access at system, domain or course-wide level? Exit.
1.29      www      8039:     if ($thisallowed=~/F/) {
                   8040: 	return 'F';
                   8041:     }
                   8042: 
1.52      www      8043: # If this is generating or modifying users, exit with special codes
1.29      www      8044: 
1.643     www      8045:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8046: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8047: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8048: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8049: 	    unless ($auname) { return $thisallowed; }
                   8050: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8051: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8052: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8053: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8054: 	}
1.52      www      8055: 	return $thisallowed;
                   8056:     }
                   8057: #
1.103     harris41 8058: # Gathered so far: system, domain and course wide privileges
1.52      www      8059: #
                   8060: # Course: See if uri or referer is an individual resource that is part of 
                   8061: # the course
                   8062: 
1.620     albertel 8063:     if ($env{'request.course.id'}) {
1.232     www      8064: 
1.1172.2.115  raeburn  8065: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8066: 
                   8067:         if ($priv eq 'mip') {
                   8068:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8069:                 return $thisallowed;
                   8070:             } else {
                   8071:                 return '';
                   8072:             }
                   8073:         }
                   8074: 
1.620     albertel 8075:        $courseprivid=$env{'request.course.id'};
                   8076:        if ($env{'request.course.sec'}) {
                   8077:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8078:        }
                   8079:        $courseprivid=~s/\_/\//;
                   8080:        my $checkreferer=1;
1.232     www      8081:        my ($match,$cond)=&is_on_map($uri);
                   8082:        if ($match) {
                   8083:            $statecond=$cond;
1.620     albertel 8084:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8085:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8086:                my $value = $1;
                   8087:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8088:                    if ($noblockcheck) {
1.1162    raeburn  8089:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8090:                    } else {
                   8091:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8092:                        if (@blockers > 0) {
                   8093:                            $thisallowed = 'B';
                   8094:                        } else {
                   8095:                            $thisallowed.=$value;
                   8096:                        }
1.1162    raeburn  8097:                    }
                   8098:                } else {
                   8099:                    $thisallowed.=$value;
                   8100:                }
1.52      www      8101:                $checkreferer=0;
                   8102:            }
1.29      www      8103:        }
1.83      www      8104:        
1.148     www      8105:        if ($checkreferer) {
1.620     albertel 8106: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8107:             unless ($refuri) {
1.800     albertel 8108:                 foreach my $key (keys(%env)) {
                   8109: 		    if ($key=~/^httpref\..*\*/) {
                   8110: 			my $pattern=$key;
1.156     www      8111:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8112:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8113:                         $pattern=~s/\//\\\//g;
1.152     www      8114:                         if ($orguri=~/$pattern/) {
1.800     albertel 8115: 			    $refuri=$env{$key};
1.148     www      8116:                         }
                   8117:                     }
1.191     harris41 8118:                 }
1.148     www      8119:             }
1.232     www      8120: 
1.148     www      8121:          if ($refuri) { 
1.152     www      8122: 	  $refuri=&declutter($refuri);
1.232     www      8123:           my ($match,$cond)=&is_on_map($refuri);
                   8124:             if ($match) {
                   8125:               my $refstatecond=$cond;
1.620     albertel 8126:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8127:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8128:                   my $value = $1;
                   8129:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8130:                       if ($noblockcheck) {
1.1162    raeburn  8131:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8132:                       } else {
                   8133:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8134:                           if (@blockers > 0) {
                   8135:                               $thisallowed = 'B';
                   8136:                           } else {
                   8137:                               $thisallowed.=$value;
                   8138:                           }
1.1162    raeburn  8139:                       }
                   8140:                   } else {
                   8141:                       $thisallowed.=$value;
                   8142:                   }
1.53      www      8143:                   $uri=$refuri;
                   8144:                   $statecond=$refstatecond;
1.52      www      8145:               }
                   8146:           }
1.148     www      8147:         }
1.29      www      8148:        }
1.52      www      8149:    }
1.29      www      8150: 
1.52      www      8151: #
1.103     harris41 8152: # Gathered now: all privileges that could apply, and condition number
1.52      www      8153: # 
                   8154: #
                   8155: # Full or no access?
                   8156: #
1.29      www      8157: 
1.52      www      8158:     if ($thisallowed=~/F/) {
                   8159: 	return 'F';
                   8160:     }
1.29      www      8161: 
1.52      www      8162:     unless ($thisallowed) {
                   8163:         return '';
                   8164:     }
1.29      www      8165: 
1.52      www      8166: # Restrictions exist, deal with them
                   8167: #
                   8168: #   C:according to course preferences
                   8169: #   R:according to resource settings
                   8170: #   L:unless locked
                   8171: #   X:according to user session state
                   8172: #
                   8173: 
                   8174: # Possibly locked functionality, check all courses
1.54      www      8175: # Locks might take effect only after 10 minutes cache expiration for other
                   8176: # courses, and 2 minutes for current course
1.52      www      8177: 
                   8178:     my $envkey;
                   8179:     if ($thisallowed=~/L/) {
1.1000    raeburn  8180:         foreach $envkey (keys(%env)) {
1.54      www      8181:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8182:                my $courseid=$2;
                   8183:                my $roleid=$1.'.'.$2;
1.92      www      8184:                $courseid=~s/^\///;
1.54      www      8185:                my $expiretime=600;
1.620     albertel 8186:                if ($env{'request.role'} eq $roleid) {
1.54      www      8187: 		  $expiretime=120;
                   8188:                }
                   8189: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8190:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8191:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8192: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8193:                }
1.620     albertel 8194:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8195:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8196: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8197:                        &log($env{'user.domain'},$env{'user.name'},
                   8198:                             $env{'user.home'},
1.57      www      8199:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8200:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8201:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8202: 		       return '';
                   8203:                    }
                   8204:                }
1.620     albertel 8205:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8206:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8207: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8208:                        &log($env{'user.domain'},$env{'user.name'},
                   8209:                             $env{'user.home'},
1.57      www      8210:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8211:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8212:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8213: 		       return '';
                   8214:                    }
                   8215:                }
                   8216: 	   }
1.29      www      8217:        }
1.52      www      8218:     }
                   8219:    
                   8220: #
                   8221: # Rest of the restrictions depend on selected course
                   8222: #
                   8223: 
1.620     albertel 8224:     unless ($env{'request.course.id'}) {
1.766     albertel 8225: 	if ($thisallowed eq 'A') {
                   8226: 	    return 'A';
1.814     raeburn  8227:         } elsif ($thisallowed eq 'B') {
                   8228:             return 'B';
1.766     albertel 8229: 	} else {
                   8230: 	    return '1';
                   8231: 	}
1.52      www      8232:     }
1.29      www      8233: 
1.52      www      8234: #
                   8235: # Now user is definitely in a course
                   8236: #
1.53      www      8237: 
                   8238: 
                   8239: # Course preferences
                   8240: 
                   8241:    if ($thisallowed=~/C/) {
1.620     albertel 8242:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8243:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8244:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8245: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8246: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8247: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8248: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8249: 			$env{'request.course.id'});
                   8250: 	   }
1.237     www      8251:            return '';
                   8252:        }
                   8253: 
1.620     albertel 8254:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8255: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8256: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8257: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8258: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8259: 			$env{'request.course.id'});
                   8260: 	   }
1.54      www      8261:            return '';
                   8262:        }
1.53      www      8263:    }
                   8264: 
                   8265: # Resource preferences
                   8266: 
                   8267:    if ($thisallowed=~/R/) {
1.620     albertel 8268:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8269:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8270: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8271: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8272: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8273: 	   }
                   8274: 	   return '';
1.54      www      8275:        }
1.53      www      8276:    }
1.30      www      8277: 
1.246     www      8278: # Restricted by state or randomout?
1.30      www      8279: 
1.52      www      8280:    if ($thisallowed=~/X/) {
1.620     albertel 8281:       if ($env{'acc.randomout'}) {
1.579     albertel 8282: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8283:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8284:             return ''; 
                   8285:          }
1.247     www      8286:       }
                   8287:       if (&condval($statecond)) {
1.52      www      8288: 	 return '2';
                   8289:       } else {
                   8290:          return '';
                   8291:       }
                   8292:    }
1.30      www      8293: 
1.766     albertel 8294:     if ($thisallowed eq 'A') {
                   8295: 	return 'A';
1.814     raeburn  8296:     } elsif ($thisallowed eq 'B') {
                   8297:         return 'B';
1.766     albertel 8298:     }
1.52      www      8299:    return 'F';
1.232     www      8300: }
1.1162    raeburn  8301: 
1.1172.2.13  raeburn  8302: # ------------------------------------------- Check construction space access
                   8303: 
                   8304: sub constructaccess {
                   8305:     my ($url,$setpriv)=@_;
                   8306: 
                   8307: # We do not allow editing of previous versions of files
                   8308:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8309: 
                   8310: # Get username and domain from URL
                   8311:     my ($ownername,$ownerdomain,$ownerhome);
                   8312: 
                   8313:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8314:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8315: 
                   8316: # The URL does not really point to any authorspace, forget it
                   8317:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8318: 
                   8319: # Now we need to see if the user has access to the authorspace of
                   8320: # $ownername at $ownerdomain
                   8321: 
                   8322:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8323: # Real author for this?
                   8324:        $ownerhome = $env{'user.home'};
                   8325:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8326:           return ($ownername,$ownerdomain,$ownerhome);
                   8327:        }
                   8328:     } else {
                   8329: # Co-author for this?
                   8330:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8331:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8332:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8333:             return ($ownername,$ownerdomain,$ownerhome);
                   8334:         }
                   8335:     }
                   8336: 
                   8337: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8338: # we might as well leave
                   8339:    unless ($setpriv) { return ''; }
                   8340: 
                   8341: # Backdoor access?
                   8342:     my $allowed=&allowed('eco',$ownerdomain);
                   8343: # Nope
                   8344:     unless ($allowed) { return ''; }
                   8345: # Looks like we may have access, but could be locked by the owner of the construction space
                   8346:     if ($allowed eq 'U') {
                   8347:         my %blocked=&get('environment',['domcoord.author'],
                   8348:                          $ownerdomain,$ownername);
                   8349: # Is blocked by owner
                   8350:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8351:     }
                   8352:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8353: # Grant temporary access
                   8354:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8355:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8356:         if (!$update) { $update = $then; }
                   8357:         my $refresh=$env{'user.refresh.time'};
                   8358:         if (!$refresh) { $refresh = $update; }
                   8359:         my $now = time;
                   8360:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8361:                            $now,'ca','constructaccess');
                   8362:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8363:         return($ownername,$ownerdomain,$ownerhome);
                   8364:     }
                   8365: # No business here
                   8366:     return '';
                   8367: }
                   8368: 
1.1172.2.66  raeburn  8369: # ----------------------------------------------------------- Content Blocking
                   8370: 
                   8371: {
                   8372: # Caches for faster Course Contents display where content blocking
                   8373: # is in operation (i.e., interval param set) for timed quiz.
                   8374: #
                   8375: # User for whom data are being temporarily cached.
                   8376: my $cacheduser='';
                   8377: # Cached blockers for this user (a hash of blocking items).
                   8378: my %cachedblockers=();
                   8379: # When the data were last cached.
                   8380: my $cachedlast='';
                   8381: 
                   8382: sub load_all_blockers {
                   8383:     my ($uname,$udom,$blocks)=@_;
                   8384:     if (($uname ne '') && ($udom ne '')) {
                   8385:         if (($cacheduser eq $uname.':'.$udom) &&
                   8386:             (abs($cachedlast-time)<5)) {
                   8387:             return;
                   8388:         }
                   8389:     }
                   8390:     $cachedlast=time;
                   8391:     $cacheduser=$uname.':'.$udom;
                   8392:     %cachedblockers = &get_commblock_resources($blocks);
                   8393: }
                   8394: 
1.1162    raeburn  8395: sub get_comm_blocks {
                   8396:     my ($cdom,$cnum) = @_;
                   8397:     if ($cdom eq '' || $cnum eq '') {
                   8398:         return unless ($env{'request.course.id'});
                   8399:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8400:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8401:     }
                   8402:     my %commblocks;
                   8403:     my $hashid=$cdom.'_'.$cnum;
                   8404:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8405:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8406:         %commblocks = %{$blocksref};
                   8407:     } else {
                   8408:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8409:         my $cachetime = 600;
                   8410:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8411:     }
                   8412:     return %commblocks;
                   8413: }
                   8414: 
1.1172.2.66  raeburn  8415: sub get_commblock_resources {
                   8416:     my ($blocks) = @_;
                   8417:     my %blockers = ();
                   8418:     return %blockers unless ($env{'request.course.id'});
                   8419:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8420:     my %commblocks;
                   8421:     if (ref($blocks) eq 'HASH') {
                   8422:         %commblocks = %{$blocks};
                   8423:     } else {
                   8424:         %commblocks = &get_comm_blocks();
                   8425:     }
1.1172.2.66  raeburn  8426:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8427:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8428:     return %blockers unless (ref($navmap));
                   8429:     my $now = time;
1.1162    raeburn  8430:     foreach my $block (keys(%commblocks)) {
                   8431:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8432:             my ($start,$end) = ($1,$2);
                   8433:             if ($start <= $now && $end >= $now) {
                   8434:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8435:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8436:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8437:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8438:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8439:                             }
                   8440:                         }
                   8441:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8442:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8443:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8444:                             }
                   8445:                         }
                   8446:                     }
                   8447:                 }
                   8448:             }
                   8449:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8450:             my $item = $1;
1.1163    raeburn  8451:             my @to_test;
1.1162    raeburn  8452:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8453:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8454:                     my @interval;
                   8455:                     my $type = 'map';
                   8456:                     if ($item eq 'course') {
                   8457:                         $type = 'course';
                   8458:                         @interval=&EXT("resource.0.interval");
                   8459:                     } else {
                   8460:                         if ($item =~ /___\d+___/) {
                   8461:                             $type = 'resource';
                   8462:                             @interval=&EXT("resource.0.interval",$item);
                   8463:                             if (ref($navmap)) {
                   8464:                                 my $res = $navmap->getBySymb($item);
                   8465:                                 push(@to_test,$res);
                   8466:                             }
1.1162    raeburn  8467:                         } else {
1.1172.2.66  raeburn  8468:                             my $mapsymb = &symbread($item,1);
                   8469:                             if ($mapsymb) {
                   8470:                                 if (ref($navmap)) {
                   8471:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8472:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8473:                                     foreach my $res (@to_test) {
                   8474:                                         my $symb = $res->symb();
                   8475:                                         next if ($symb eq $mapsymb);
                   8476:                                         if ($symb ne '') {
                   8477:                                             @interval=&EXT("resource.0.interval",$symb);
                   8478:                                             if ($interval[1] eq 'map') {
                   8479:                                                 last;
1.1162    raeburn  8480:                                             }
                   8481:                                         }
                   8482:                                     }
                   8483:                                 }
                   8484:                             }
                   8485:                         }
1.1172.2.66  raeburn  8486:                     }
1.1172.2.118.  .1(raebu 8487:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8488:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8489:                         my $first_access;
                   8490:                         if ($type eq 'resource') {
                   8491:                             $first_access=&get_first_access($interval[1],$item);
                   8492:                         } elsif ($type eq 'map') {
                   8493:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8494:                         } else {
                   8495:                             $first_access=&get_first_access($interval[1]);
                   8496:                         }
                   8497:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8498:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8499:                             if ($timesup > $now) {
                   8500:                                 my $activeblock;
                   8501:                                 foreach my $res (@to_test) {
                   8502:                                     if ($res->answerable()) {
                   8503:                                         $activeblock = 1;
                   8504:                                         last;
                   8505:                                     }
                   8506:                                 }
                   8507:                                 if ($activeblock) {
                   8508:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8509:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8510:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8511:                                          }
                   8512:                                     }
                   8513:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8514:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8515:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8516:                                         }
1.1162    raeburn  8517:                                     }
                   8518:                                 }
                   8519:                             }
                   8520:                         }
                   8521:                     }
                   8522:                 }
                   8523:             }
                   8524:         }
                   8525:     }
1.1172.2.66  raeburn  8526:     return %blockers;
1.1162    raeburn  8527: }
                   8528: 
1.1172.2.66  raeburn  8529: sub has_comm_blocking {
                   8530:     my ($priv,$symb,$uri,$blocks) = @_;
                   8531:     my @blockers;
                   8532:     return unless ($env{'request.course.id'});
                   8533:     return unless ($priv eq 'bre');
                   8534:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8535:     return if ($env{'request.state'} eq 'construct');
                   8536:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8537:     return unless (keys(%cachedblockers) > 0);
                   8538:     my (%possibles,@symbs);
                   8539:     if (!$symb) {
                   8540:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8541:     }
1.1172.2.66  raeburn  8542:     if ($symb) {
                   8543:         @symbs = ($symb);
                   8544:     } elsif (keys(%possibles)) {
                   8545:         @symbs = keys(%possibles);
                   8546:     }
                   8547:     my $noblock;
                   8548:     foreach my $symb (@symbs) {
                   8549:         last if ($noblock);
                   8550:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8551:         foreach my $block (keys(%cachedblockers)) {
                   8552:             if ($block =~ /^firstaccess____(.+)$/) {
                   8553:                 my $item = $1;
                   8554:                 if (($item eq $map) || ($item eq $symb)) {
                   8555:                     $noblock = 1;
                   8556:                     last;
                   8557:                 }
1.1162    raeburn  8558:             }
1.1172.2.66  raeburn  8559:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8560:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8561:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8562:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8563:                             push(@blockers,$block);
                   8564:                         }
                   8565:                     }
                   8566:                 }
                   8567:             }
                   8568:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8569:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8570:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8571:                         push(@blockers,$block);
                   8572:                     }
                   8573:                 }
1.1162    raeburn  8574:             }
                   8575:         }
                   8576:     }
1.1172.2.66  raeburn  8577:     return if ($noblock);
                   8578:     return @blockers;
                   8579: }
1.1162    raeburn  8580: }
                   8581: 
1.1172.2.66  raeburn  8582: # -------------------------------- Deversion and split uri into path an filename
                   8583: 
1.1133    foxr     8584: #
1.1172.2.66  raeburn  8585: #   Removes the version from a URI and
1.1133    foxr     8586: #   splits it in to its filename and path to the filename.
                   8587: #   Seems like File::Basename could have done this more clearly.
                   8588: #   Parameters:
                   8589: #      $uri   - input URI
                   8590: #   Returns:
                   8591: #     Two element list consisting of 
                   8592: #     $pathname  - the URI up to and excluding the trailing /
                   8593: #     $filename  - The part of the URI following the last /
                   8594: #  NOTE:
                   8595: #    Another realization of this is simply:
                   8596: #    use File::Basename;
                   8597: #    ...
                   8598: #    $uri = shift;
                   8599: #    $filename = basename($uri);
                   8600: #    $path     = dirname($uri);
                   8601: #    return ($filename, $path);
                   8602: #
                   8603: #     The implementation below is probably faster however.
                   8604: #
1.710     albertel 8605: sub split_uri_for_cond {
                   8606:     my $uri=&deversion(&declutter(shift));
                   8607:     my @uriparts=split(/\//,$uri);
                   8608:     my $filename=pop(@uriparts);
                   8609:     my $pathname=join('/',@uriparts);
                   8610:     return ($pathname,$filename);
                   8611: }
1.232     www      8612: # --------------------------------------------------- Is a resource on the map?
                   8613: 
                   8614: sub is_on_map {
1.710     albertel 8615:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8616:     #Trying to find the conditional for the file
1.620     albertel 8617:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8618: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8619:     if ($match) {
1.289     bowersj2 8620: 	return (1,$1);
                   8621:     } else {
1.434     www      8622: 	return (0,0);
1.289     bowersj2 8623:     }
1.12      www      8624: }
                   8625: 
1.427     www      8626: # --------------------------------------------------------- Get symb from alias
                   8627: 
                   8628: sub get_symb_from_alias {
                   8629:     my $symb=shift;
                   8630:     my ($map,$resid,$url)=&decode_symb($symb);
                   8631: # Already is a symb
                   8632:     if ($url) { return $symb; }
                   8633: # Must be an alias
                   8634:     my $aliassymb='';
                   8635:     my %bighash;
1.620     albertel 8636:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8637:                             &GDBM_READER(),0640)) {
                   8638:         my $rid=$bighash{'mapalias_'.$symb};
                   8639: 	if ($rid) {
                   8640: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8641: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8642: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8643: 	}
                   8644:         untie %bighash;
                   8645:     }
                   8646:     return $aliassymb;
                   8647: }
                   8648: 
1.12      www      8649: # ----------------------------------------------------------------- Define Role
                   8650: 
                   8651: sub definerole {
                   8652:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8653:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8654:     foreach my $role (split(':',$sysrole)) {
                   8655: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8656:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8657:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8658: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8659:                return "refused:s:$crole&$cqual"; 
                   8660:             }
                   8661:         }
1.191     harris41 8662:     }
1.800     albertel 8663:     foreach my $role (split(':',$domrole)) {
                   8664: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8665:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8666:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8667: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8668:                return "refused:d:$crole&$cqual"; 
                   8669:             }
                   8670:         }
1.191     harris41 8671:     }
1.800     albertel 8672:     foreach my $role (split(':',$courole)) {
                   8673: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8674:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8675:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8676: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8677:                return "refused:c:$crole&$cqual"; 
                   8678:             }
                   8679:         }
1.191     harris41 8680:     }
1.1172.2.84  raeburn  8681:     my $uhome;
                   8682:     if (($uname ne '') && ($udom ne '')) {
                   8683:         $uhome = &homeserver($uname,$udom);
                   8684:         return $uhome if ($uhome eq 'no_host');
                   8685:     } else {
                   8686:         $uname = $env{'user.name'};
                   8687:         $udom = $env{'user.domain'};
                   8688:         $uhome = $env{'user.home'};
                   8689:     }
1.620     albertel 8690:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8691:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8692:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8693:     return reply($command,$uhome);
1.12      www      8694:   } else {
                   8695:     return 'refused';
                   8696:   }
1.105     harris41 8697: }
                   8698: 
                   8699: # ---------------- Make a metadata query against the network of library servers
                   8700: 
                   8701: sub metadata_query {
1.1172.2.33  raeburn  8702:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8703:     my %rhash;
1.845     albertel 8704:     my %libserv = &all_library();
1.244     matthew  8705:     my @server_list = (defined($server_array) ? @$server_array
                   8706:                                               : keys(%libserv) );
                   8707:     for my $server (@server_list) {
1.1172.2.33  raeburn  8708:         my $domains = '';
                   8709:         if (ref($domains_hash) eq 'HASH') {
                   8710:             $domains = $domains_hash->{$server};    
                   8711:         }
1.118     harris41 8712: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8713: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8714: 	    $rhash{$server}=$reply;
                   8715: 	}
                   8716: 	else {
                   8717: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8718: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8719: 			     $server);
                   8720: 	    $rhash{$server}=$reply;
                   8721: 	}
1.112     harris41 8722:     }
1.118     harris41 8723:     return \%rhash;
1.240     www      8724: }
                   8725: 
                   8726: # ----------------------------------------- Send log queries and wait for reply
                   8727: 
                   8728: sub log_query {
                   8729:     my ($uname,$udom,$query,%filters)=@_;
                   8730:     my $uhome=&homeserver($uname,$udom);
                   8731:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8732:     my $uhost=&hostname($uhome);
1.800     albertel 8733:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8734:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8735:                        $uhome);
1.479     albertel 8736:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8737:     return get_query_reply($queryid);
                   8738: }
                   8739: 
1.818     raeburn  8740: # -------------------------- Update MySQL table for portfolio file
                   8741: 
                   8742: sub update_portfolio_table {
1.821     raeburn  8743:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8744:     if ($group ne '') {
                   8745:         $file_name =~s /^\Q$group\E//;
                   8746:     }
1.818     raeburn  8747:     my $homeserver = &homeserver($uname,$udom);
                   8748:     my $queryid=
1.821     raeburn  8749:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8750:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8751:     my $reply = &get_query_reply($queryid);
                   8752:     return $reply;
                   8753: }
                   8754: 
1.899     raeburn  8755: # -------------------------- Update MySQL allusers table
                   8756: 
                   8757: sub update_allusers_table {
                   8758:     my ($uname,$udom,$names) = @_;
                   8759:     my $homeserver = &homeserver($uname,$udom);
                   8760:     my $queryid=
                   8761:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8762:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8763:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8764:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8765:                'generation='.&escape($names->{'generation'}).'%%'.
                   8766:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8767:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8768:     return;
1.899     raeburn  8769: }
                   8770: 
1.508     raeburn  8771: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8772: 
                   8773: sub fetch_enrollment_query {
1.511     raeburn  8774:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8775:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8776:     my $maxtries = 1;
1.508     raeburn  8777:     if ($context eq 'automated') {
                   8778:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8779:         $sleep = 2;
                   8780:         $loopmax = 100;
1.547     raeburn  8781:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8782:     } else {
                   8783:         $homeserver = &homeserver($cnum,$dom);
                   8784:     }
1.838     albertel 8785:     my $host=&hostname($homeserver);
1.506     raeburn  8786:     my $cmd = '';
1.1000    raeburn  8787:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8788:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8789:     }
                   8790:     $cmd =~ s/%%$//;
                   8791:     $cmd = &escape($cmd);
                   8792:     my $query = 'fetchenrollment';
1.620     albertel 8793:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8794:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8795:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8796:         return 'error: '.$queryid;
                   8797:     }
1.1172.2.93  raeburn  8798:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8799:     my $tries = 1;
                   8800:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8801:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8802:         $tries ++;
                   8803:     }
1.526     raeburn  8804:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8805:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8806:     } else {
1.901     albertel 8807:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8808:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8809:             foreach my $line (@responses) {
                   8810:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8811:                 $$replyref{$key} = $value;
                   8812:             }
                   8813:         } else {
1.1117    foxr     8814:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8815:             foreach my $line (@responses) {
                   8816:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8817:                 $$replyref{$key} = $value;
                   8818:                 if ($value > 0) {
1.800     albertel 8819:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8820:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8821:                         my $destname = $pathname.'/'.$filename;
                   8822:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8823:                         if ($xml_classlist =~ /^error/) {
                   8824:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8825:                         } else {
1.1172.2.96  raeburn  8826:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8827:                                 print FILE &unescape($xml_classlist);
                   8828:                                 close(FILE);
1.526     raeburn  8829:                             } else {
                   8830:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8831:                             }
                   8832:                         }
                   8833:                     }
                   8834:                 }
                   8835:             }
                   8836:         }
                   8837:         return 'ok';
                   8838:     }
                   8839:     return 'error';
                   8840: }
                   8841: 
1.242     www      8842: sub get_query_reply {
1.1172.2.79  raeburn  8843:     my ($queryid,$sleep,$loopmax) = @_;
                   8844:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8845:         $sleep = 0.2;
                   8846:     }
                   8847:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8848:         $loopmax = 100;
                   8849:     }
1.1117    foxr     8850:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8851:     my $reply='';
1.1172.2.79  raeburn  8852:     for (1..$loopmax) {
                   8853: 	sleep($sleep);
1.240     www      8854:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8855: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8856: 		$reply = join('',<$fh>);
                   8857: 		close($fh);
1.240     www      8858: 	   } else { return 'error: reply_file_error'; }
1.242     www      8859:            return &unescape($reply);
                   8860: 	}
1.240     www      8861:     }
1.242     www      8862:     return 'timeout:'.$queryid;
1.240     www      8863: }
                   8864: 
                   8865: sub courselog_query {
1.241     www      8866: #
                   8867: # possible filters:
                   8868: # url: url or symb
                   8869: # username
                   8870: # domain
                   8871: # action: view, submit, grade
                   8872: # start: timestamp
                   8873: # end: timestamp
                   8874: #
1.240     www      8875:     my (%filters)=@_;
1.620     albertel 8876:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8877:     if ($filters{'url'}) {
                   8878: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8879:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8880:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8881:     }
1.620     albertel 8882:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8883:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8884:     return &log_query($cname,$cdom,'courselog',%filters);
                   8885: }
                   8886: 
                   8887: sub userlog_query {
1.858     raeburn  8888: #
                   8889: # possible filters:
                   8890: # action: log check role
                   8891: # start: timestamp
                   8892: # end: timestamp
                   8893: #
1.240     www      8894:     my ($uname,$udom,%filters)=@_;
                   8895:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8896: }
                   8897: 
1.506     raeburn  8898: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8899: 
                   8900: sub auto_run {
1.508     raeburn  8901:     my ($cnum,$cdom) = @_;
1.876     raeburn  8902:     my $response = 0;
                   8903:     my $settings;
                   8904:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8905:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8906:         $settings = $domconfig{'autoenroll'};
                   8907:         if ($settings->{'run'} eq '1') {
                   8908:             $response = 1;
                   8909:         }
                   8910:     } else {
1.934     raeburn  8911:         my $homeserver;
                   8912:         if (&is_course($cdom,$cnum)) {
                   8913:             $homeserver = &homeserver($cnum,$cdom);
                   8914:         } else {
                   8915:             $homeserver = &domain($cdom,'primary');
                   8916:         }
                   8917:         if ($homeserver ne 'no_host') {
                   8918:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8919:         }
1.876     raeburn  8920:     }
1.506     raeburn  8921:     return $response;
                   8922: }
1.776     albertel 8923: 
1.506     raeburn  8924: sub auto_get_sections {
1.508     raeburn  8925:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8926:     my $homeserver;
                   8927:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8928:         $homeserver = &homeserver($cnum,$cdom);
                   8929:     }
                   8930:     if (!defined($homeserver)) { 
                   8931:         if ($cdom =~ /^$match_domain$/) {
                   8932:             $homeserver = &domain($cdom,'primary');
                   8933:         }
                   8934:     }
                   8935:     my @secs;
                   8936:     if (defined($homeserver)) {
                   8937:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8938:         unless ($response eq 'refused') {
                   8939:             @secs = split(/:/,$response);
                   8940:         }
1.506     raeburn  8941:     }
                   8942:     return @secs;
                   8943: }
1.776     albertel 8944: 
1.506     raeburn  8945: sub auto_new_course {
1.1099    raeburn  8946:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8947:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8948:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8949:     return $response;
                   8950: }
1.776     albertel 8951: 
1.506     raeburn  8952: sub auto_validate_courseID {
1.508     raeburn  8953:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8954:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8955:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8956:     return $response;
                   8957: }
1.776     albertel 8958: 
1.1007    raeburn  8959: sub auto_validate_instcode {
1.1020    raeburn  8960:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8961:     my ($homeserver,$response);
                   8962:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8963:         $homeserver = &homeserver($cnum,$cdom);
                   8964:     }
                   8965:     if (!defined($homeserver)) {
                   8966:         if ($cdom =~ /^$match_domain$/) {
                   8967:             $homeserver = &domain($cdom,'primary');
                   8968:         }
                   8969:     }
1.1065    raeburn  8970:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8971:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8972:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8973:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8974: }
                   8975: 
1.506     raeburn  8976: sub auto_create_password {
1.873     raeburn  8977:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8978:     my ($homeserver,$response);
1.506     raeburn  8979:     my $create_passwd = 0;
                   8980:     my $authchk = '';
1.873     raeburn  8981:     if ($udom =~ /^$match_domain$/) {
                   8982:         $homeserver = &domain($udom,'primary');
                   8983:     }
                   8984:     if ($homeserver eq '') {
                   8985:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8986:             $homeserver = &homeserver($cnum,$cdom);
                   8987:         }
                   8988:     }
                   8989:     if ($homeserver eq '') {
                   8990:         $authchk = 'nodomain';
1.506     raeburn  8991:     } else {
1.873     raeburn  8992:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8993:         if ($response eq 'refused') {
                   8994:             $authchk = 'refused';
                   8995:         } else {
1.901     albertel 8996:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8997:         }
1.506     raeburn  8998:     }
                   8999:     return ($authparam,$create_passwd,$authchk);
                   9000: }
                   9001: 
1.706     raeburn  9002: sub auto_photo_permission {
                   9003:     my ($cnum,$cdom,$students) = @_;
                   9004:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9005:     my ($outcome,$perm_reqd,$conditions) = 
                   9006: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9007:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9008: 	return (undef,undef);
                   9009:     }
1.706     raeburn  9010:     return ($outcome,$perm_reqd,$conditions);
                   9011: }
                   9012: 
                   9013: sub auto_checkphotos {
                   9014:     my ($uname,$udom,$pid) = @_;
                   9015:     my $homeserver = &homeserver($uname,$udom);
                   9016:     my ($result,$resulttype);
                   9017:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9018: 				   &escape($uname).':'.&escape($pid),
                   9019: 				   $homeserver));
1.709     albertel 9020:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9021: 	return (undef,undef);
                   9022:     }
1.706     raeburn  9023:     if ($outcome) {
                   9024:         ($result,$resulttype) = split(/:/,$outcome);
                   9025:     } 
                   9026:     return ($result,$resulttype);
                   9027: }
                   9028: 
                   9029: sub auto_photochoice {
                   9030:     my ($cnum,$cdom) = @_;
                   9031:     my $homeserver = &homeserver($cnum,$cdom);
                   9032:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9033: 						       &escape($cdom),
                   9034: 						       $homeserver)));
1.709     albertel 9035:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9036: 	return (undef,undef);
                   9037:     }
1.706     raeburn  9038:     return ($update,$comment);
                   9039: }
                   9040: 
                   9041: sub auto_photoupdate {
                   9042:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9043:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9044:     my $host=&hostname($homeserver);
1.706     raeburn  9045:     my $cmd = '';
                   9046:     my $maxtries = 1;
1.800     albertel 9047:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9048:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9049:     }
                   9050:     $cmd =~ s/%%$//;
                   9051:     $cmd = &escape($cmd);
                   9052:     my $query = 'institutionalphotos';
                   9053:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9054:     unless ($queryid=~/^\Q$host\E\_/) {
                   9055:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9056:         return 'error: '.$queryid;
                   9057:     }
                   9058:     my $reply = &get_query_reply($queryid);
                   9059:     my $tries = 1;
                   9060:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9061:         $reply = &get_query_reply($queryid);
                   9062:         $tries ++;
                   9063:     }
                   9064:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9065:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9066:     } else {
                   9067:         my @responses = split(/:/,$reply);
                   9068:         my $outcome = shift(@responses); 
                   9069:         foreach my $item (@responses) {
                   9070:             my ($key,$value) = split(/=/,$item);
                   9071:             $$photo{$key} = $value;
                   9072:         }
                   9073:         return $outcome;
                   9074:     }
                   9075:     return 'error';
                   9076: }
                   9077: 
1.521     raeburn  9078: sub auto_instcode_format {
1.793     albertel 9079:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9080: 	$cat_order) = @_;
1.521     raeburn  9081:     my $courses = '';
1.772     raeburn  9082:     my @homeservers;
1.521     raeburn  9083:     if ($caller eq 'global') {
1.841     albertel 9084: 	my %servers = &get_servers($codedom,'library');
                   9085: 	foreach my $tryserver (keys(%servers)) {
                   9086: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9087: 		push(@homeservers,$tryserver);
                   9088: 	    }
1.584     raeburn  9089:         }
1.1022    raeburn  9090:     } elsif ($caller eq 'requests') {
                   9091:         if ($codedom =~ /^$match_domain$/) {
                   9092:             my $chome = &domain($codedom,'primary');
                   9093:             unless ($chome eq 'no_host') {
                   9094:                 push(@homeservers,$chome);
                   9095:             }
                   9096:         }
1.521     raeburn  9097:     } else {
1.772     raeburn  9098:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9099:     }
1.793     albertel 9100:     foreach my $code (keys(%{$instcodes})) {
                   9101:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9102:     }
                   9103:     chop($courses);
1.772     raeburn  9104:     my $ok_response = 0;
                   9105:     my $response;
                   9106:     while (@homeservers > 0 && $ok_response == 0) {
                   9107:         my $server = shift(@homeservers); 
                   9108:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9109:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9110:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9111: 		split(/:/,$response);
1.772     raeburn  9112:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9113:             push(@{$codetitles},&str2array($codetitles_str));
                   9114:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9115:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9116:             $ok_response = 1;
                   9117:         }
                   9118:     }
                   9119:     if ($ok_response) {
1.521     raeburn  9120:         return 'ok';
1.772     raeburn  9121:     } else {
                   9122:         return $response;
1.521     raeburn  9123:     }
                   9124: }
                   9125: 
1.792     raeburn  9126: sub auto_instcode_defaults {
                   9127:     my ($domain,$returnhash,$code_order) = @_;
                   9128:     my @homeservers;
1.841     albertel 9129: 
                   9130:     my %servers = &get_servers($domain,'library');
                   9131:     foreach my $tryserver (keys(%servers)) {
                   9132: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9133: 	    push(@homeservers,$tryserver);
                   9134: 	}
1.792     raeburn  9135:     }
1.841     albertel 9136: 
1.792     raeburn  9137:     my $response;
1.841     albertel 9138:     foreach my $server (@homeservers) {
1.792     raeburn  9139:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9140:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9141: 	
                   9142: 	foreach my $pair (split(/\&/,$response)) {
                   9143: 	    my ($name,$value)=split(/\=/,$pair);
                   9144: 	    if ($name eq 'code_order') {
                   9145: 		@{$code_order} = split(/\&/,&unescape($value));
                   9146: 	    } else {
                   9147: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9148: 	    }
                   9149: 	}
                   9150: 	return 'ok';
1.792     raeburn  9151:     }
1.841     albertel 9152: 
                   9153:     return $response;
1.1003    raeburn  9154: }
                   9155: 
                   9156: sub auto_possible_instcodes {
1.1007    raeburn  9157:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9158:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9159:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9160:         return;
                   9161:     }
1.1003    raeburn  9162:     my (@homeservers,$uhome);
                   9163:     if (defined(&domain($domain,'primary'))) {
                   9164:         $uhome=&domain($domain,'primary');
                   9165:         push(@homeservers,&domain($domain,'primary'));
                   9166:     } else {
                   9167:         my %servers = &get_servers($domain,'library');
                   9168:         foreach my $tryserver (keys(%servers)) {
                   9169:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9170:                 push(@homeservers,$tryserver);
                   9171:             }
                   9172:         }
                   9173:     }
                   9174:     my $response;
                   9175:     foreach my $server (@homeservers) {
                   9176:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9177:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9178:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9179:             split(':',$response);
                   9180:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9181:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9182:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9183:             my ($name,$value)=split('=',$item);
                   9184:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9185:         }
                   9186:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9187:             my ($name,$value)=split('=',$item);
                   9188:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9189:         }
                   9190:         return 'ok';
                   9191:     }
                   9192:     return $response;
                   9193: }
1.792     raeburn  9194: 
1.1010    raeburn  9195: sub auto_courserequest_checks {
                   9196:     my ($dom) = @_;
1.1020    raeburn  9197:     my ($homeserver,%validations);
                   9198:     if ($dom =~ /^$match_domain$/) {
                   9199:         $homeserver = &domain($dom,'primary');
                   9200:     }
                   9201:     unless ($homeserver eq 'no_host') {
                   9202:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9203:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9204:             my @items = split(/&/,$response);
                   9205:             foreach my $item (@items) {
                   9206:                 my ($key,$value) = split('=',$item);
                   9207:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9208:             }
                   9209:         }
                   9210:     }
1.1010    raeburn  9211:     return %validations; 
                   9212: }
                   9213: 
1.1020    raeburn  9214: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9215:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9216:     my ($homeserver,$response);
                   9217:     if ($dom =~ /^$match_domain$/) {
                   9218:         $homeserver = &domain($dom,'primary');
                   9219:     }
1.1172.2.43  raeburn  9220:     unless ($homeserver eq 'no_host') {
                   9221:         my $customdata;
                   9222:         if (ref($custominfo) eq 'HASH') {
                   9223:             $customdata = &freeze_escape($custominfo);
                   9224:         }
1.1020    raeburn  9225:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9226:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9227:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9228:                                     $customdata,$homeserver));
1.1020    raeburn  9229:     }
                   9230:     return $response;
                   9231: }
                   9232: 
1.777     albertel 9233: sub auto_validate_class_sec {
1.918     raeburn  9234:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9235:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9236:     my $ownerlist;
                   9237:     if (ref($owners) eq 'ARRAY') {
                   9238:         $ownerlist = join(',',@{$owners});
                   9239:     } else {
                   9240:         $ownerlist = $owners;
                   9241:     }
1.773     raeburn  9242:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9243:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9244:     return $response;
                   9245: }
                   9246: 
1.1172.2.94  raeburn  9247: sub auto_validate_instclasses {
                   9248:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9249:     my ($homeserver,%validations);
                   9250:     $homeserver = &homeserver($cnum,$cdom);
                   9251:     unless ($homeserver eq 'no_host') {
                   9252:         my $ownerlist;
                   9253:         if (ref($owners) eq 'ARRAY') {
                   9254:             $ownerlist = join(',',@{$owners});
                   9255:         } else {
                   9256:             $ownerlist = $owners;
                   9257:         }
                   9258:         if (ref($classesref) eq 'HASH') {
                   9259:             my $classes = &freeze_escape($classesref);
                   9260:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9261:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9262:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9263:                 my @items = split(/&/,$response);
                   9264:                 foreach my $item (@items) {
                   9265:                     my ($key,$value) = split('=',$item);
                   9266:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9267:                 }
                   9268:             }
                   9269:         }
                   9270:     }
                   9271:     return %validations;
                   9272: }
                   9273: 
1.1172.2.38  raeburn  9274: sub auto_crsreq_update {
                   9275:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9276:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9277:     my ($homeserver,%crsreqresponse);
                   9278:     if ($cdom =~ /^$match_domain$/) {
                   9279:         $homeserver = &domain($cdom,'primary');
                   9280:     }
                   9281:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9282:         my $info;
                   9283:         if (ref($inbound) eq 'HASH') {
                   9284:             $info = &freeze_escape($inbound);
                   9285:         }
                   9286:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9287:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9288:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9289:                             &escape($title).':'.&escape($code).':'.
                   9290:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9291:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9292:             my @items = split(/&/,$response);
                   9293:             foreach my $item (@items) {
                   9294:                 my ($key,$value) = split('=',$item);
                   9295:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9296:             }
                   9297:         }
                   9298:     }
                   9299:     return \%crsreqresponse;
                   9300: }
                   9301: 
1.1172.2.78  raeburn  9302: sub auto_export_grades {
                   9303:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9304:     my ($homeserver,%exportresponse);
                   9305:     if ($cdom =~ /^$match_domain$/) {
                   9306:         $homeserver = &domain($cdom,'primary');
                   9307:     }
                   9308:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9309:         my $info;
                   9310:         if (ref($inforef) eq 'HASH') {
                   9311:             $info = &freeze_escape($inforef);
                   9312:         }
                   9313:         if (ref($gradesref) eq 'HASH') {
                   9314:             my $grades = &freeze_escape($gradesref);
                   9315:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9316:                                 $info.':'.$grades,$homeserver);
                   9317:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9318:                 my @items = split(/&/,$response);
                   9319:                 foreach my $item (@items) {
                   9320:                     my ($key,$value) = split('=',$item);
                   9321:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9322:                 }
                   9323:             }
                   9324:         }
                   9325:     }
                   9326:     return \%exportresponse;
                   9327: }
                   9328: 
1.1172.2.68  raeburn  9329: sub check_instcode_cloning {
                   9330:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9331:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9332:         return;
                   9333:     }
                   9334:     my $canclone;
                   9335:     if (@{$code_order} > 0) {
                   9336:         my $instcoderegexp ='^';
                   9337:         my @clonecodes = split(/\&/,$cloner);
                   9338:         foreach my $item (@{$code_order}) {
                   9339:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9340:                 foreach my $pair (@clonecodes) {
                   9341:                     my ($key,$val) = split(/\=/,$pair,2);
                   9342:                     $val = &unescape($val);
                   9343:                     if ($key eq $item) {
                   9344:                         $instcoderegexp .= '('.$val.')';
                   9345:                         last;
                   9346:                     }
                   9347:                 }
                   9348:             } else {
                   9349:                 $instcoderegexp .= $codedefaults->{$item};
                   9350:             }
                   9351:         }
                   9352:         $instcoderegexp .= '$';
                   9353:         my (@from,@to);
                   9354:         eval {
                   9355:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9356:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9357:         };
                   9358:         if ((@from > 0) && (@to > 0)) {
                   9359:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9360:             if (!@diffs) {
                   9361:                 $canclone = 1;
                   9362:             }
                   9363:         }
                   9364:     }
                   9365:     return $canclone;
                   9366: }
                   9367: 
                   9368: sub default_instcode_cloning {
                   9369:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9370:     my (%codedefaults,@code_order,$canclone);
                   9371:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9372:         %codedefaults = %{$codedefaultsref};
                   9373:         @code_order = @{$codeorderref};
                   9374:     } elsif ($clonedom) {
                   9375:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9376:     }
                   9377:     if (($domdefclone) && (@code_order)) {
                   9378:         my @clonecodes = split(/\+/,$domdefclone);
                   9379:         my $instcoderegexp ='^';
                   9380:         foreach my $item (@code_order) {
                   9381:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9382:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9383:             } else {
                   9384:                 $instcoderegexp .= $codedefaults{$item};
                   9385:             }
                   9386:         }
                   9387:         $instcoderegexp .= '$';
                   9388:         my (@from,@to);
                   9389:         eval {
                   9390:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9391:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9392:         };
                   9393:         if ((@from > 0) && (@to > 0)) {
                   9394:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9395:             if (!@diffs) {
                   9396:                 $canclone = 1;
                   9397:             }
                   9398:         }
                   9399:     }
                   9400:     return $canclone;
                   9401: }
                   9402: 
1.679     raeburn  9403: # ------------------------------------------------------- Course Group routines
                   9404: 
                   9405: sub get_coursegroups {
1.809     raeburn  9406:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9407:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9408: }
                   9409: 
1.679     raeburn  9410: sub modify_coursegroup {
                   9411:     my ($cdom,$cnum,$groupsettings) = @_;
                   9412:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9413: }
                   9414: 
1.809     raeburn  9415: sub toggle_coursegroup_status {
                   9416:     my ($cdom,$cnum,$group,$action) = @_;
                   9417:     my ($from_namespace,$to_namespace);
                   9418:     if ($action eq 'delete') {
                   9419:         $from_namespace = 'coursegroups';
                   9420:         $to_namespace = 'deleted_groups';
                   9421:     } else {
                   9422:         $from_namespace = 'deleted_groups';
                   9423:         $to_namespace = 'coursegroups';
                   9424:     }
                   9425:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9426:     if (my $tmp = &error(%curr_group)) {
                   9427:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9428:         return ('read error',$tmp);
                   9429:     } else {
                   9430:         my %savedsettings = %curr_group; 
1.809     raeburn  9431:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9432:         my $deloutcome;
                   9433:         if ($result eq 'ok') {
1.809     raeburn  9434:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9435:         } else {
                   9436:             return ('write error',$result);
                   9437:         }
                   9438:         if ($deloutcome eq 'ok') {
                   9439:             return 'ok';
                   9440:         } else {
                   9441:             return ('delete error',$deloutcome);
                   9442:         }
                   9443:     }
                   9444: }
                   9445: 
1.679     raeburn  9446: sub modify_group_roles {
1.957     raeburn  9447:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9448:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9449:     my $role = 'gr/'.&escape($userprivs);
                   9450:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9451:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9452:     if ($result eq 'ok') {
                   9453:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9454:     }
1.679     raeburn  9455:     return $result;
                   9456: }
                   9457: 
                   9458: sub modify_coursegroup_membership {
                   9459:     my ($cdom,$cnum,$membership) = @_;
                   9460:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9461:     return $result;
                   9462: }
                   9463: 
1.682     raeburn  9464: sub get_active_groups {
                   9465:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9466:     my $now = time;
                   9467:     my %groups = ();
                   9468:     foreach my $key (keys(%env)) {
1.811     albertel 9469:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9470:             my ($start,$end) = split(/\./,$env{$key});
                   9471:             if (($end!=0) && ($end<$now)) { next; }
                   9472:             if (($start!=0) && ($start>$now)) { next; }
                   9473:             if ($1 eq $cdom && $2 eq $cnum) {
                   9474:                 $groups{$3} = $env{$key} ;
                   9475:             }
                   9476:         }
                   9477:     }
                   9478:     return %groups;
                   9479: }
                   9480: 
1.683     raeburn  9481: sub get_group_membership {
                   9482:     my ($cdom,$cnum,$group) = @_;
                   9483:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9484: }
                   9485: 
                   9486: sub get_users_groups {
                   9487:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9488:     my @usersgroups;
1.683     raeburn  9489:     my $cachetime=1800;
                   9490: 
                   9491:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9492:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9493:     if (defined($cached)) {
1.734     albertel 9494:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9495:     } else {  
                   9496:         $grouplist = '';
1.816     raeburn  9497:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9498:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9499:         my $access_end = $env{'course.'.$courseid.
                   9500:                               '.default_enrollment_end_date'};
                   9501:         my $now = time;
                   9502:         foreach my $key (keys(%roleshash)) {
                   9503:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9504:                 my $group = $1;
                   9505:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9506:                     my $start = $2;
                   9507:                     my $end = $1;
                   9508:                     if ($start == -1) { next; } # deleted from group
                   9509:                     if (($start!=0) && ($start>$now)) { next; }
                   9510:                     if (($end!=0) && ($end<$now)) {
                   9511:                         if ($access_end && $access_end < $now) {
                   9512:                             if ($access_end - $end < 86400) {
                   9513:                                 push(@usersgroups,$group);
1.733     raeburn  9514:                             }
                   9515:                         }
1.817     raeburn  9516:                         next;
1.733     raeburn  9517:                     }
1.817     raeburn  9518:                     push(@usersgroups,$group);
1.683     raeburn  9519:                 }
                   9520:             }
                   9521:         }
1.817     raeburn  9522:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9523:         $grouplist = join(':',@usersgroups);
                   9524:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9525:     }
1.733     raeburn  9526:     return @usersgroups;
1.683     raeburn  9527: }
                   9528: 
                   9529: sub devalidate_getgroups_cache {
                   9530:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9531:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9532: 
1.683     raeburn  9533:     my $hashid="$udom:$uname:$courseid";
                   9534:     &devalidate_cache_new('getgroups',$hashid);
                   9535: }
                   9536: 
1.12      www      9537: # ------------------------------------------------------------------ Plain Text
                   9538: 
                   9539: sub plaintext {
1.988     raeburn  9540:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9541:     if ($short =~ m{^cr/}) {
1.758     albertel 9542: 	return (split('/',$short))[-1];
                   9543:     }
1.742     raeburn  9544:     if (!defined($cid)) {
                   9545:         $cid = $env{'request.course.id'};
                   9546:     }
                   9547:     my %rolenames = (
1.1008    raeburn  9548:                       Course    => 'std',
                   9549:                       Community => 'alt1',
1.742     raeburn  9550:                     );
1.1037    raeburn  9551:     if ($cid ne '') {
                   9552:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9553:             unless ($forcedefault) {
                   9554:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9555:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9556:                 return &Apache::lonlocal::mt($roletext);
                   9557:             }
                   9558:         }
                   9559:     }
                   9560:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9561:         (defined($rolenames{$type})) && 
                   9562:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9563:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9564:     } elsif ($cid ne '') {
                   9565:         my $crstype = $env{'course.'.$cid.'.type'};
                   9566:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9567:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9568:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9569:         }
1.742     raeburn  9570:     }
1.1037    raeburn  9571:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9572: }
                   9573: 
                   9574: # ----------------------------------------------------------------- Assign Role
                   9575: 
                   9576: sub assignrole {
1.957     raeburn  9577:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9578:         $context)=@_;
1.21      www      9579:     my $mrole;
                   9580:     if ($role =~ /^cr\//) {
1.393     www      9581:         my $cwosec=$url;
1.811     albertel 9582:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9583: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9584:            my $refused = 1;
                   9585:            if ($context eq 'requestcourses') {
                   9586:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9587:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9588:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9589:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9590:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9591:                            if ($crsenv{'internal.courseowner'} eq
                   9592:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9593:                                $refused = '';
                   9594:                            }
                   9595:                        }
                   9596:                    }
                   9597:                }
                   9598:            }
                   9599:            if ($refused) {
                   9600:                &logthis('Refused custom assignrole: '.
                   9601:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9602:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9603:                return 'refused';
                   9604:            }
1.104     www      9605:         }
1.21      www      9606:         $mrole='cr';
1.678     raeburn  9607:     } elsif ($role =~ /^gr\//) {
                   9608:         my $cwogrp=$url;
1.811     albertel 9609:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9610:         unless (&allowed('mdg',$cwogrp)) {
                   9611:             &logthis('Refused group assignrole: '.
                   9612:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9613:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9614:             return 'refused';
                   9615:         }
                   9616:         $mrole='gr';
1.21      www      9617:     } else {
1.82      www      9618:         my $cwosec=$url;
1.811     albertel 9619:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9620:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9621:             my $refused;
                   9622:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9623:                 if (!(&allowed('c'.$role,$url))) {
                   9624:                     $refused = 1;
                   9625:                 }
                   9626:             } else {
                   9627:                 $refused = 1;
                   9628:             }
1.947     raeburn  9629:             if ($refused) {
1.1045    raeburn  9630:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9631:                 if (!$selfenroll && $context eq 'course') {
                   9632:                     my %crsenv;
                   9633:                     if ($role eq 'cc' || $role eq 'co') {
                   9634:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9635:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9636:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9637:                                 if ($crsenv{'internal.courseowner'} eq 
                   9638:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9639:                                     $refused = '';
                   9640:                                 }
                   9641:                             }
                   9642:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9643:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9644:                                 if ($crsenv{'internal.courseowner'} eq 
                   9645:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9646:                                     $refused = '';
                   9647:                                 }
                   9648:                             }
                   9649:                         }
                   9650:                     }
                   9651:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9652:                     $refused = '';
1.1017    raeburn  9653:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9654:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9655:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9656:                         my $wrongcc;
                   9657:                         if ($cnum =~ /^$match_community$/) {
                   9658:                             $wrongcc = 1 if ($role eq 'cc');
                   9659:                         } else {
                   9660:                             $wrongcc = 1 if ($role eq 'co');
                   9661:                         }
                   9662:                         unless ($wrongcc) {
                   9663:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9664:                             if ($crsenv{'internal.courseowner'} eq 
                   9665:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9666:                                 $refused = '';
                   9667:                             }
1.1017    raeburn  9668:                         }
                   9669:                     }
1.1172.2.9  raeburn  9670:                 } elsif ($context eq 'requestauthor') {
                   9671:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9672:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9673:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9674:                             $refused = '';
                   9675:                         } else {
                   9676:                             my %domdefaults = &get_domain_defaults($udom);
                   9677:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9678:                                 my $checkbystatus;
                   9679:                                 if ($env{'user.adv'}) {
                   9680:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9681:                                     if ($disposition eq 'automatic') {
                   9682:                                         $refused = '';
                   9683:                                     } elsif ($disposition eq '') {
                   9684:                                         $checkbystatus = 1;
                   9685:                                     }
                   9686:                                 } else {
                   9687:                                     $checkbystatus = 1;
                   9688:                                 }
                   9689:                                 if ($checkbystatus) {
                   9690:                                     if ($env{'environment.inststatus'}) {
                   9691:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9692:                                         foreach my $type (@inststatuses) {
                   9693:                                             if (($type ne '') &&
                   9694:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9695:                                                 $refused = '';
                   9696:                                             }
                   9697:                                         }
                   9698:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9699:                                         $refused = '';
                   9700:                                     }
                   9701:                                 }
                   9702:                             }
                   9703:                         }
                   9704:                     }
1.1017    raeburn  9705:                 }
                   9706:                 if ($refused) {
1.947     raeburn  9707:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9708:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9709: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9710:                     return 'refused';
                   9711:                 }
1.932     raeburn  9712:             }
1.1131    raeburn  9713:         } elsif ($role eq 'au') {
                   9714:             if ($url ne '/'.$udom.'/') {
                   9715:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9716:                          ' to assign author role for '.$uname.':'.$udom.
                   9717:                          ' in domain: '.$url.' refused (wrong domain).');
                   9718:                 return 'refused';
                   9719:             }
1.104     www      9720:         }
1.21      www      9721:         $mrole=$role;
                   9722:     }
1.620     albertel 9723:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9724:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9725:     if ($end) { $command.='_'.$end; }
1.21      www      9726:     if ($start) {
                   9727: 	if ($end) { 
1.81      www      9728:            $command.='_'.$start; 
1.21      www      9729:         } else {
1.81      www      9730:            $command.='_0_'.$start;
1.21      www      9731:         }
                   9732:     }
1.739     raeburn  9733:     my $origstart = $start;
                   9734:     my $origend = $end;
1.957     raeburn  9735:     my $delflag;
1.357     www      9736: # actually delete
                   9737:     if ($deleteflag) {
1.373     www      9738: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9739: # modify command to delete the role
1.620     albertel 9740:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9741:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9742: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9743: # set start and finish to negative values for userrolelog
                   9744:            $start=-1;
                   9745:            $end=-1;
1.957     raeburn  9746:            $delflag = 1;
1.357     www      9747:         }
                   9748:     }
                   9749: # send command
1.349     www      9750:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9751: # log new user role if status is ok
1.349     www      9752:     if ($answer eq 'ok') {
1.663     raeburn  9753: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9754:         if (($role eq 'cc') || ($role eq 'in') ||
                   9755:             ($role eq 'ep') || ($role eq 'ad') ||
                   9756:             ($role eq 'ta') || ($role eq 'st') ||
                   9757:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9758:             ($role eq 'co')) {
1.1172.2.13  raeburn  9759: # for course roles, perform group memberships changes triggered by role change.
                   9760:             unless ($role =~ /^gr/) {
                   9761:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9762:                                                  $origstart,$selfenroll,$context);
                   9763:             }
1.1172.2.9  raeburn  9764:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9765:                            $selfenroll,$context);
                   9766:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9767:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9768:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9769:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9770:                            $context);
                   9771:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9772:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9773:                              $context);
                   9774:         }
1.1053    raeburn  9775:         if ($role eq 'cc') {
                   9776:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9777:         }
1.349     www      9778:     }
                   9779:     return $answer;
1.169     harris41 9780: }
                   9781: 
1.1053    raeburn  9782: sub autoupdate_coowners {
                   9783:     my ($url,$end,$start,$uname,$udom) = @_;
                   9784:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9785:     if (($cdom ne '') && ($cnum ne '')) {
                   9786:         my $now = time;
                   9787:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9788:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9789:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9790:             my $instcode = $coursehash{'internal.coursecode'};
                   9791:             if ($instcode ne '') {
1.1056    raeburn  9792:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9793:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9794:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9795:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9796:                         if ($result eq 'valid') {
                   9797:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9798:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9799:                                     push(@newcoowners,$coowner);
                   9800:                                 }
                   9801:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9802:                                     push(@newcoowners,$uname.':'.$udom);
                   9803:                                 }
                   9804:                                 @newcoowners = sort(@newcoowners);
                   9805:                             } else {
                   9806:                                 push(@newcoowners,$uname.':'.$udom);
                   9807:                             }
                   9808:                         } else {
                   9809:                             if ($coursehash{'internal.co-owners'}) {
                   9810:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9811:                                     unless ($coowner eq $uname.':'.$udom) {
                   9812:                                         push(@newcoowners,$coowner);
                   9813:                                     }
                   9814:                                 }
                   9815:                                 unless (@newcoowners > 0) {
                   9816:                                     $delcoowners = 1;
                   9817:                                     $coowners = '';
                   9818:                                 }
                   9819:                             }
                   9820:                         }
                   9821:                         if (@newcoowners || $delcoowners) {
                   9822:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9823:                                             $delcoowners,@newcoowners);
                   9824:                         }
                   9825:                     }
                   9826:                 }
                   9827:             }
                   9828:         }
                   9829:     }
                   9830: }
                   9831: 
                   9832: sub store_coowners {
                   9833:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9834:     my $cid = $cdom.'_'.$cnum;
                   9835:     my ($coowners,$delresult,$putresult);
                   9836:     if (@newcoowners) {
                   9837:         $coowners = join(',',@newcoowners);
                   9838:         my %coownershash = (
                   9839:                             'internal.co-owners' => $coowners,
                   9840:                            );
                   9841:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9842:         if ($putresult eq 'ok') {
                   9843:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9844:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9845:             }
                   9846:         }
                   9847:     }
                   9848:     if ($delcoowners) {
                   9849:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9850:         if ($delresult eq 'ok') {
                   9851:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9852:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9853:             }
                   9854:         }
                   9855:     }
                   9856:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9857:         my %crsinfo =
                   9858:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9859:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9860:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9861:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9862:         }
                   9863:     }
                   9864: }
                   9865: 
1.169     harris41 9866: # -------------------------------------------------- Modify user authentication
1.197     www      9867: # Overrides without validation
                   9868: 
1.169     harris41 9869: sub modifyuserauth {
                   9870:     my ($udom,$uname,$umode,$upass)=@_;
                   9871:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9872:     my $allowed;
                   9873:     if (&allowed('mau',$udom)) {
                   9874:         $allowed = 1;
                   9875:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9876:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9877:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9878:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9879:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9880:         if (($cdom ne '') && ($cnum ne '')) {
                   9881:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9882:             if ($is_owner) {
                   9883:                 $allowed = 1;
                   9884:             }
                   9885:         }
                   9886:     }
                   9887:     unless ($allowed) { return 'refused'; }
1.197     www      9888:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9889:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9890:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9891:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9892: 		     &escape($upass),$uhome);
1.620     albertel 9893:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9894:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9895:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9896:     &log($udom,,$uname,$uhome,
1.620     albertel 9897:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9898:                                      $env{'user.name'}.', '.$umode.
1.197     www      9899:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9900:     unless ($reply eq 'ok') {
1.197     www      9901:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9902: 	return 'error: '.$reply;
                   9903:     }   
1.170     harris41 9904:     return 'ok';
1.80      www      9905: }
                   9906: 
1.81      www      9907: # --------------------------------------------------------------- Modify a user
1.80      www      9908: 
1.81      www      9909: sub modifyuser {
1.206     matthew  9910:     my ($udom,    $uname, $uid,
                   9911:         $umode,   $upass, $first,
                   9912:         $middle,  $last,  $gene,
1.1058    raeburn  9913:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9914:     $udom= &LONCAPA::clean_domain($udom);
                   9915:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9916:     my $showcandelete = 'none';
                   9917:     if (ref($candelete) eq 'ARRAY') {
                   9918:         if (@{$candelete} > 0) {
                   9919:             $showcandelete = join(', ',@{$candelete});
                   9920:         }
                   9921:     }
1.81      www      9922:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9923:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9924: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9925:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9926:                                      ' desiredhome not specified'). 
1.620     albertel 9927:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9928:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9929:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9930:     my $newuser;
                   9931:     if ($uhome eq 'no_host') {
                   9932:         $newuser = 1;
                   9933:     }
1.80      www      9934: # ----------------------------------------------------------------- Create User
1.406     albertel 9935:     if (($uhome eq 'no_host') && 
                   9936: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9937:         my $unhome='';
1.844     albertel 9938:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9939:             $unhome = $desiredhome;
1.620     albertel 9940: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9941: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9942:         } else { # load balancing routine for determining $unhome
1.81      www      9943:             my $loadm=10000000;
1.841     albertel 9944: 	    my %servers = &get_servers($udom,'library');
                   9945: 	    foreach my $tryserver (keys(%servers)) {
                   9946: 		my $answer=reply('load',$tryserver);
                   9947: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9948: 		    $loadm=$answer;
                   9949: 		    $unhome=$tryserver;
                   9950: 		}
1.80      www      9951: 	    }
                   9952:         }
                   9953:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9954: 	    return 'error: unable to find a home server for '.$uname.
                   9955:                    ' in domain '.$udom;
1.80      www      9956:         }
                   9957:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9958:                          &escape($upass),$unhome);
                   9959: 	unless ($reply eq 'ok') {
                   9960:             return 'error: '.$reply;
                   9961:         }   
1.230     stredwic 9962:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9963:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9964: 	    return 'error: unable verify users home machine.';
1.80      www      9965:         }
1.209     matthew  9966:     }   # End of creation of new user
1.80      www      9967: # ---------------------------------------------------------------------- Add ID
                   9968:     if ($uid) {
                   9969:        $uid=~tr/A-Z/a-z/;
                   9970:        my %uidhash=&idrget($udom,$uname);
1.196     www      9971:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9972:          && (!$forceid)) {
1.80      www      9973: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9974: 	      return 'error: user id "'.$uid.'" does not match '.
                   9975:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9976:           }
                   9977:        } else {
                   9978: 	  &idput($udom,($uname => $uid));
                   9979:        }
                   9980:     }
                   9981: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9982:     my @tmp=&get('environment',
1.899     raeburn  9983: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9984:                     'permanentemail','inststatus'],
1.134     albertel 9985: 		   $udom,$uname);
1.1075    raeburn  9986:     my (%names,%oldnames);
1.313     matthew  9987:     if ($tmp[0] =~ m/^error:.*/) { 
                   9988:         %names=(); 
                   9989:     } else {
                   9990:         %names = @tmp;
1.1075    raeburn  9991:         %oldnames = %names;
1.313     matthew  9992:     }
1.388     www      9993: #
1.1058    raeburn  9994: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9995: # of users did not contain them), do not overwrite existing values
                   9996: # unless field is in $candelete array ref.  
                   9997: #
                   9998: 
                   9999:     my @fields = ('firstname','middlename','lastname','generation',
                   10000:                   'permanentemail','id');
                   10001:     my %newvalues;
                   10002:     if (ref($candelete) eq 'ARRAY') {
                   10003:         foreach my $field (@fields) {
                   10004:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10005:                 if ($field eq 'firstname') {
                   10006:                     $names{$field} = $first;
                   10007:                 } elsif ($field eq 'middlename') {
                   10008:                     $names{$field} = $middle;
                   10009:                 } elsif ($field eq 'lastname') {
                   10010:                     $names{$field} = $last;
                   10011:                 } elsif ($field eq 'generation') { 
                   10012:                     $names{$field} = $gene;
                   10013:                 } elsif ($field eq 'permanentemail') {
                   10014:                     $names{$field} = $email;
                   10015:                 } elsif ($field eq 'id') {
                   10016:                     $names{$field}  = $uid;
                   10017:                 }
                   10018:             }
                   10019:         }
                   10020:     }
1.388     www      10021:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10022:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10023:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10024:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10025:     if ($email) {
                   10026:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10027:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10028:     }
1.899     raeburn  10029:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10030:     if (defined($inststatus)) {
                   10031:         $names{'inststatus'} = '';
                   10032:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10033:         if (ref($usertypes) eq 'HASH') {
                   10034:             my @okstatuses; 
                   10035:             foreach my $item (split(/:/,$inststatus)) {
                   10036:                 if (defined($usertypes->{$item})) {
                   10037:                     push(@okstatuses,$item);  
                   10038:                 }
                   10039:             }
                   10040:             if (@okstatuses) {
                   10041:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10042:             }
                   10043:         }
                   10044:     }
1.1075    raeburn  10045:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10046:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10047:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10048:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10049:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10050:     } else {
                   10051:         $logmsg .= ' during self creation';
                   10052:     }
1.1075    raeburn  10053:     my $changed;
                   10054:     if ($newuser) {
                   10055:         $changed = 1;
                   10056:     } else {
                   10057:         foreach my $field (@fields) {
                   10058:             if ($names{$field} ne $oldnames{$field}) {
                   10059:                 $changed = 1;
                   10060:                 last;
                   10061:             }
                   10062:         }
                   10063:     }
                   10064:     unless ($changed) {
                   10065:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10066:         &logthis($logmsg);
                   10067:         return 'ok';
                   10068:     }
                   10069:     my $reply = &put('environment', \%names, $udom,$uname);
                   10070:     if ($reply ne 'ok') { 
                   10071:         return 'error: '.$reply;
                   10072:     }
1.1087    raeburn  10073:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10074:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10075:     }
1.1075    raeburn  10076:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10077:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10078:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10079:     &logthis($logmsg);
1.134     albertel 10080:     return 'ok';
1.80      www      10081: }
                   10082: 
1.81      www      10083: # -------------------------------------------------------------- Modify student
1.80      www      10084: 
1.81      www      10085: sub modifystudent {
                   10086:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10087:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10088:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10089:     if (!$cid) {
1.620     albertel 10090: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10091: 	    return 'not_in_class';
                   10092: 	}
1.80      www      10093:     }
                   10094: # --------------------------------------------------------------- Make the user
1.81      www      10095:     my $reply=&modifyuser
1.209     matthew  10096: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10097:          $desiredhome,$email,$inststatus);
1.80      www      10098:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10099:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10100:     # student's environment
1.297     matthew  10101:     $uid = undef if (!$forceid);
1.455     albertel 10102:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10103: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10104:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10105:     return $reply;
                   10106: }
                   10107: 
                   10108: sub modify_student_enrollment {
1.1172.2.23  raeburn  10109:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10110:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10111:     my ($cdom,$cnum,$chome);
                   10112:     if (!$cid) {
1.620     albertel 10113: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10114: 	    return 'not_in_class';
                   10115: 	}
1.620     albertel 10116: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10117: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10118:     } else {
                   10119: 	($cdom,$cnum)=split(/_/,$cid);
                   10120:     }
1.620     albertel 10121:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10122:     if (!$chome) {
1.457     raeburn  10123: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10124:     }
1.455     albertel 10125:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10126:     # Make sure the user exists
1.81      www      10127:     my $uhome=&homeserver($uname,$udom);
                   10128:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10129: 	return 'error: no such user';
                   10130:     }
1.297     matthew  10131:     # Get student data if we were not given enough information
                   10132:     if (!defined($first)  || $first  eq '' || 
                   10133:         !defined($last)   || $last   eq '' || 
                   10134:         !defined($uid)    || $uid    eq '' || 
                   10135:         !defined($middle) || $middle eq '' || 
                   10136:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10137:         # They did not supply us with enough data to enroll the student, so
                   10138:         # we need to pick up more information.
1.297     matthew  10139:         my %tmp = &get('environment',
1.294     matthew  10140:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10141:                        ,$udom,$uname);
                   10142: 
1.800     albertel 10143:         #foreach my $key (keys(%tmp)) {
                   10144:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10145:         #}
1.294     matthew  10146:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10147:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10148:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10149:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10150:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10151:     }
1.556     albertel 10152:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10153:     my $user = "$uname:$udom";
                   10154:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10155:     my $reply=cput('classlist',
1.1148    raeburn  10156: 		   {$user => 
1.1172.2.76  raeburn  10157: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10158: 		   $cdom,$cnum);
1.1148    raeburn  10159:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10160:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10161:     } else { 
1.81      www      10162: 	return 'error: '.$reply;
                   10163:     }
1.297     matthew  10164:     # Add student role to user
1.83      www      10165:     my $uurl='/'.$cid;
1.81      www      10166:     $uurl=~s/\_/\//g;
                   10167:     if ($usec) {
                   10168: 	$uurl.='/'.$usec;
                   10169:     }
1.1148    raeburn  10170:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10171:                              $selfenroll,$context);
                   10172:     if ($result ne 'ok') {
                   10173:         if ($old_entry{$user} ne '') {
                   10174:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10175:         } else {
                   10176:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10177:         }
                   10178:     }
                   10179:     return $result; 
1.21      www      10180: }
                   10181: 
1.556     albertel 10182: sub format_name {
                   10183:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10184:     my $name;
                   10185:     if ($first ne 'lastname') {
                   10186: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10187:     } else {
                   10188: 	if ($lastname=~/\S/) {
                   10189: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10190: 	    $name=~s/\s+,/,/;
                   10191: 	} else {
                   10192: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10193: 	}
                   10194:     }
                   10195:     $name=~s/^\s+//;
                   10196:     $name=~s/\s+$//;
                   10197:     $name=~s/\s+/ /g;
                   10198:     return $name;
                   10199: }
                   10200: 
1.84      www      10201: # ------------------------------------------------- Write to course preferences
                   10202: 
                   10203: sub writecoursepref {
                   10204:     my ($courseid,%prefs)=@_;
                   10205:     $courseid=~s/^\///;
                   10206:     $courseid=~s/\_/\//g;
                   10207:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10208:     my $chome=homeserver($cnum,$cdomain);
                   10209:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10210: 	return 'error: no such course';
                   10211:     }
                   10212:     my $cstring='';
1.800     albertel 10213:     foreach my $pref (keys(%prefs)) {
                   10214: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10215:     }
1.84      www      10216:     $cstring=~s/\&$//;
                   10217:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10218: }
                   10219: 
                   10220: # ---------------------------------------------------------- Make/modify course
                   10221: 
                   10222: sub createcourse {
1.741     raeburn  10223:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10224:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10225:     $url=&declutter($url);
                   10226:     my $cid='';
1.1028    raeburn  10227:     if ($context eq 'requestcourses') {
                   10228:         my $can_create = 0;
                   10229:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10230:         if ($udom eq $ownerdom) {
                   10231:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10232:                                   $context)) {
                   10233:                 $can_create = 1;
                   10234:             }
                   10235:         } else {
                   10236:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10237:                                            $category);
                   10238:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10239:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10240:                 if (@curr > 0) {
                   10241:                     my @options = qw(approval validate autolimit);
                   10242:                     my $optregex = join('|',@options);
                   10243:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10244:                         $can_create = 1;
                   10245:                     }
                   10246:                 }
                   10247:             }
                   10248:         }
                   10249:         if ($can_create) {
                   10250:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10251:                 unless (&allowed('ccc',$udom)) {
                   10252:                     return 'refused'; 
                   10253:                 }
1.1017    raeburn  10254:             }
                   10255:         } else {
                   10256:             return 'refused';
                   10257:         }
1.1028    raeburn  10258:     } elsif (!&allowed('ccc',$udom)) {
                   10259:         return 'refused';
1.84      www      10260:     }
1.1011    raeburn  10261: # --------------------------------------------------------------- Get Unique ID
                   10262:     my $uname;
                   10263:     if ($cnum =~ /^$match_courseid$/) {
                   10264:         my $chome=&homeserver($cnum,$udom,'true');
                   10265:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10266:             $uname = $cnum;
                   10267:         } else {
1.1038    raeburn  10268:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10269:         }
                   10270:     } else {
1.1038    raeburn  10271:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10272:     }
                   10273:     return $uname if ($uname =~ /^error/);
                   10274: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10275:     if (!defined($course_server)) {
                   10276:         if (defined(&domain($udom,'primary'))) {
                   10277:             $course_server = &domain($udom,'primary');
                   10278:         } else {
                   10279:             $course_server = $env{'user.home'}; 
                   10280:         }
                   10281:     }
                   10282:     my %host_servers =
                   10283:         &Apache::lonnet::get_servers($udom,'library');
                   10284:     unless ($host_servers{$course_server}) {
                   10285:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10286:     }
1.84      www      10287: # ------------------------------------------------------------- Make the course
                   10288:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10289:                       $course_server);
1.84      www      10290:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10291:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10292:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10293: 	return 'error: no such course';
                   10294:     }
1.271     www      10295: # ----------------------------------------------------------------- Course made
1.516     raeburn  10296: # log existence
1.1029    raeburn  10297:     my $now = time;
1.918     raeburn  10298:     my $newcourse = {
                   10299:                     $udom.'_'.$uname => {
1.921     raeburn  10300:                                      description => $description,
                   10301:                                      inst_code   => $inst_code,
                   10302:                                      owner       => $course_owner,
                   10303:                                      type        => $crstype,
1.1029    raeburn  10304:                                      creator     => $env{'user.name'}.':'.
                   10305:                                                     $env{'user.domain'},
                   10306:                                      created     => $now,
                   10307:                                      context     => $context,
1.918     raeburn  10308:                                                 },
                   10309:                     };
1.921     raeburn  10310:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10311: # set toplevel url
1.271     www      10312:     my $topurl=$url;
                   10313:     unless ($nonstandard) {
                   10314: # ------------------------------------------ For standard courses, make top url
                   10315:         my $mapurl=&clutter($url);
1.278     www      10316:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10317:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10318: <map>
                   10319: <resource id="1" type="start"></resource>
                   10320: <resource id="2" src="$mapurl"></resource>
                   10321: <resource id="3" type="finish"></resource>
                   10322: <link index="1" from="1" to="2"></link>
                   10323: <link index="2" from="2" to="3"></link>
                   10324: </map>
                   10325: ENDINITMAP
                   10326:         $topurl=&declutter(
1.638     albertel 10327:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10328:                           );
                   10329:     }
                   10330: # ----------------------------------------------------------- Write preferences
1.84      www      10331:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10332:                      ('description'              => $description,
                   10333:                       'url'                      => $topurl,
                   10334:                       'internal.creator'         => $env{'user.name'}.':'.
                   10335:                                                     $env{'user.domain'},
                   10336:                       'internal.created'         => $now,
                   10337:                       'internal.creationcontext' => $context)
                   10338:                     );
1.84      www      10339:     return '/'.$udom.'/'.$uname;
                   10340: }
                   10341: 
1.1011    raeburn  10342: # ------------------------------------------------------------------- Create ID
                   10343: sub generate_coursenum {
1.1038    raeburn  10344:     my ($udom,$crstype) = @_;
1.1011    raeburn  10345:     my $domdesc = &domain($udom);
                   10346:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10347:     my $first;
                   10348:     if ($crstype eq 'Community') {
                   10349:         $first = '0';
                   10350:     } else {
                   10351:         $first = int(1+rand(9)); 
                   10352:     } 
                   10353:     my $uname=$first.
1.1011    raeburn  10354:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10355:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10356:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10357: # ----------------------------------------------- Make sure that does not exist
                   10358:     my $uhome=&homeserver($uname,$udom,'true');
                   10359:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10360:         if ($crstype eq 'Community') {
                   10361:             $first = '0';
                   10362:         } else {
                   10363:             $first = int(1+rand(9));
                   10364:         }
                   10365:         $uname=$first.
1.1011    raeburn  10366:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10367:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10368:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10369:         $uhome=&homeserver($uname,$udom,'true');
                   10370:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10371:             return 'error: unable to generate unique course-ID';
                   10372:         }
                   10373:     }
                   10374:     return $uname;
                   10375: }
                   10376: 
1.813     albertel 10377: sub is_course {
1.1167    droeschl 10378:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10379:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10380:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10381:     my $uhome=&homeserver($cnum,$cdom);
                   10382:     my $iscourse;
                   10383:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10384:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10385:     } else {
                   10386:         my $hashid = $cdom.':'.$cnum;
                   10387:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10388:         unless (defined($cached)) {
                   10389:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10390:                                         $cnum,undef,undef,'.');
                   10391:             $iscourse = 0;
                   10392:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10393:                 $iscourse = 1;
                   10394:             }
                   10395:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10396:         }
                   10397:     }
                   10398:     return unless($iscourse);
1.1167    droeschl 10399:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10400: }
                   10401: 
1.1015    raeburn  10402: sub store_userdata {
                   10403:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10404:     my $result;
1.1016    raeburn  10405:     if ($datakey ne '') {
1.1013    raeburn  10406:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10407:             if ($udom eq '' || $uname eq '') {
                   10408:                 $udom = $env{'user.domain'};
                   10409:                 $uname = $env{'user.name'};
                   10410:             }
                   10411:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10412:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10413:                 $result = 'error: no_host';
                   10414:             } else {
                   10415:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10416:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10417: 
                   10418:                 my $namevalue='';
                   10419:                 foreach my $key (keys(%{$storehash})) {
                   10420:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10421:                 }
                   10422:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10423:                 unless ($namespace eq 'courserequests') {
                   10424:                     $datakey = &escape($datakey);
                   10425:                 }
1.1105    raeburn  10426:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10427:                                   $namevalue,$uhome);
1.1013    raeburn  10428:             }
                   10429:         } else {
                   10430:             $result = 'error: data to store was not a hash reference'; 
                   10431:         }
                   10432:     } else {
                   10433:         $result= 'error: invalid requestkey'; 
                   10434:     }
                   10435:     return $result;
                   10436: }
                   10437: 
1.21      www      10438: # ---------------------------------------------------------- Assign Custom Role
                   10439: 
                   10440: sub assigncustomrole {
1.957     raeburn  10441:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10442:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10443:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10444: }
                   10445: 
                   10446: # ----------------------------------------------------------------- Revoke Role
                   10447: 
                   10448: sub revokerole {
1.957     raeburn  10449:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10450:     my $now=time;
1.965     raeburn  10451:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10452: }
                   10453: 
                   10454: # ---------------------------------------------------------- Revoke Custom Role
                   10455: 
                   10456: sub revokecustomrole {
1.957     raeburn  10457:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10458:     my $now=time;
1.357     www      10459:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10460:            $deleteflag,$selfenroll,$context);
1.17      www      10461: }
                   10462: 
1.533     banghart 10463: # ------------------------------------------------------------ Disk usage
1.535     albertel 10464: sub diskusage {
1.955     raeburn  10465:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10466:     $directorypath =~ s/\/$//;
                   10467:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10468:                        .&escape($getpropath).':'.&escape($uname).':'
                   10469:                        .&escape($udom),homeserver($uname,$udom));
                   10470:     if ($listing eq 'unknown_cmd') {
                   10471:         if ($getpropath) {
                   10472:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10473:         }
                   10474:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10475:     }
1.514     albertel 10476:     return $listing;
1.512     banghart 10477: }
                   10478: 
1.566     banghart 10479: sub is_locked {
1.1096    raeburn  10480:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10481:     my @check;
                   10482:     my $is_locked;
1.1093    raeburn  10483:     push (@check,$file_name);
1.613     albertel 10484:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10485: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10486:     my ($tmp)=keys(%locked);
                   10487:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10488:     
1.566     banghart 10489:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10490:         $is_locked = 'false';
                   10491:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10492:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10493:                $is_locked = 'true';
1.1096    raeburn  10494:                if (ref($which) eq 'ARRAY') {
                   10495:                    push(@{$which},$entry);
                   10496:                } else {
                   10497:                    last;
                   10498:                }
1.745     raeburn  10499:            }
                   10500:        }
1.566     banghart 10501:     } else {
                   10502:         $is_locked = 'false';
                   10503:     }
1.1093    raeburn  10504:     return $is_locked;
1.566     banghart 10505: }
                   10506: 
1.759     albertel 10507: sub declutter_portfile {
                   10508:     my ($file) = @_;
1.833     albertel 10509:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10510:     return $file;
                   10511: }
                   10512: 
1.559     banghart 10513: # ------------------------------------------------------------- Mark as Read Only
                   10514: 
                   10515: sub mark_as_readonly {
                   10516:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10517:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10518:     my ($tmp)=keys(%current_permissions);
                   10519:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10520:     foreach my $file (@{$files}) {
1.759     albertel 10521: 	$file = &declutter_portfile($file);
1.561     banghart 10522:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10523:     }
1.613     albertel 10524:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10525:     return;
                   10526: }
                   10527: 
1.572     banghart 10528: # ------------------------------------------------------------Save Selected Files
                   10529: 
                   10530: sub save_selected_files {
                   10531:     my ($user, $path, @files) = @_;
                   10532:     my $filename = $user."savedfiles";
1.573     banghart 10533:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10534:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10535:     foreach my $file (@files) {
1.620     albertel 10536:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10537:     }
                   10538:     foreach my $file (@other_files) {
1.574     banghart 10539:         print (OUT $file."\n");
1.572     banghart 10540:     }
1.574     banghart 10541:     close (OUT);
1.572     banghart 10542:     return 'ok';
                   10543: }
                   10544: 
1.574     banghart 10545: sub clear_selected_files {
                   10546:     my ($user) = @_;
                   10547:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10548:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10549:     print (OUT undef);
                   10550:     close (OUT);
                   10551:     return ("ok");    
                   10552: }
                   10553: 
1.572     banghart 10554: sub files_in_path {
                   10555:     my ($user, $path) = @_;
                   10556:     my $filename = $user."savedfiles";
                   10557:     my %return_files;
1.1172.2.96  raeburn  10558:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10559:     while (my $line_in = <IN>) {
1.574     banghart 10560:         chomp ($line_in);
                   10561:         my @paths_and_file = split (m!/!, $line_in);
                   10562:         my $file_part = pop (@paths_and_file);
                   10563:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10564:         $path_part.='/';
                   10565:         my $path_and_file = $path_part.$file_part;
                   10566:         if ($path_part eq $path) {
                   10567:             $return_files{$file_part}= 'selected';
                   10568:         }
                   10569:     }
1.574     banghart 10570:     close (IN);
                   10571:     return (\%return_files);
1.572     banghart 10572: }
                   10573: 
                   10574: # called in portfolio select mode, to show files selected NOT in current directory
                   10575: sub files_not_in_path {
                   10576:     my ($user, $path) = @_;
                   10577:     my $filename = $user."savedfiles";
                   10578:     my @return_files;
                   10579:     my $path_part;
1.1172.2.96  raeburn  10580:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10581:     while (my $line = <IN>) {
1.572     banghart 10582:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10583:         my @paths_and_file = split(m|/|, $line);
                   10584:         my $file_part = pop(@paths_and_file);
                   10585:         chomp($file_part);
                   10586:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10587:         $path_part .= '/';
                   10588:         my $path_and_file = $path_part.$file_part;
                   10589:         if ($path_part ne $path) {
1.800     albertel 10590:             push(@return_files, ($path_and_file));
1.572     banghart 10591:         }
                   10592:     }
1.800     albertel 10593:     close(OUT);
1.574     banghart 10594:     return (@return_files);
1.572     banghart 10595: }
                   10596: 
1.745     raeburn  10597: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10598: 
1.745     raeburn  10599: sub get_portfile_permissions {
                   10600:     my ($domain,$user) = @_;
1.613     albertel 10601:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10602:     my ($tmp)=keys(%current_permissions);
                   10603:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10604:     return \%current_permissions;
                   10605: }
                   10606: 
                   10607: #---------------------------------------------Get portfolio file access controls
                   10608: 
1.749     raeburn  10609: sub get_access_controls {
1.745     raeburn  10610:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10611:     my %access;
                   10612:     my $real_file = $file;
                   10613:     $file =~ s/\.meta$//;
1.745     raeburn  10614:     if (defined($file)) {
1.749     raeburn  10615:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10616:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10617:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10618:             }
                   10619:         }
1.745     raeburn  10620:     } else {
1.749     raeburn  10621:         foreach my $key (keys(%{$current_permissions})) {
                   10622:             if ($key =~ /\0accesscontrol$/) {
                   10623:                 if (defined($group)) {
                   10624:                     if ($key !~ m-^\Q$group\E/-) {
                   10625:                         next;
                   10626:                     }
                   10627:                 }
                   10628:                 my ($fullpath) = split(/\0/,$key);
                   10629:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10630:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10631:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10632:                     }
                   10633:                 }
                   10634:             }
                   10635:         }
                   10636:     }
                   10637:     return %access;
                   10638: }
                   10639: 
                   10640: sub modify_access_controls {
                   10641:     my ($file_name,$changes,$domain,$user)=@_;
                   10642:     my ($outcome,$deloutcome);
                   10643:     my %store_permissions;
                   10644:     my %new_values;
                   10645:     my %new_control;
                   10646:     my %translation;
                   10647:     my @deletions = ();
                   10648:     my $now = time;
                   10649:     if (exists($$changes{'activate'})) {
                   10650:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10651:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10652:             my $numnew = scalar(@newitems);
                   10653:             for (my $i=0; $i<$numnew; $i++) {
                   10654:                 my $newkey = $newitems[$i];
                   10655:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10656:                 if ($newkey =~ /^\d+:/) { 
                   10657:                     $newkey =~ s/^(\d+)/$newid/;
                   10658:                     $translation{$1} = $newid;
                   10659:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10660:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10661:                     $translation{$1} = $newid;
                   10662:                 }
1.749     raeburn  10663:                 $new_values{$file_name."\0".$newkey} = 
                   10664:                                           $$changes{'activate'}{$newitems[$i]};
                   10665:                 $new_control{$newkey} = $now;
                   10666:             }
                   10667:         }
                   10668:     }
                   10669:     my %todelete;
                   10670:     my %changed_items;
                   10671:     foreach my $action ('delete','update') {
                   10672:         if (exists($$changes{$action})) {
                   10673:             if (ref($$changes{$action}) eq 'HASH') {
                   10674:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10675:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10676:                     if ($action eq 'delete') { 
                   10677:                         $todelete{$itemnum} = 1;
                   10678:                     } else {
                   10679:                         $changed_items{$itemnum} = $key;
                   10680:                     }
                   10681:                 }
1.745     raeburn  10682:             }
                   10683:         }
1.749     raeburn  10684:     }
                   10685:     # get lock on access controls for file.
                   10686:     my $lockhash = {
                   10687:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10688:                                                        ':'.$env{'user.domain'},
                   10689:                    }; 
                   10690:     my $tries = 0;
                   10691:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10692:    
1.1172.2.79  raeburn  10693:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10694:         $tries ++;
1.1172.2.79  raeburn  10695:         sleep(0.1);
1.749     raeburn  10696:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10697:     }
                   10698:     if ($gotlock eq 'ok') {
                   10699:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10700:         my ($tmp)=keys(%curr_permissions);
                   10701:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10702:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10703:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10704:             if (ref($curr_controls) eq 'HASH') {
                   10705:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10706:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10707:                     if (defined($todelete{$itemnum})) {
                   10708:                         push(@deletions,$file_name."\0".$control_item);
                   10709:                     } else {
                   10710:                         if (defined($changed_items{$itemnum})) {
                   10711:                             $new_control{$changed_items{$itemnum}} = $now;
                   10712:                             push(@deletions,$file_name."\0".$control_item);
                   10713:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10714:                         } else {
                   10715:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10716:                         }
                   10717:                     }
1.745     raeburn  10718:                 }
                   10719:             }
                   10720:         }
1.970     raeburn  10721:         my ($group);
                   10722:         if (&is_course($domain,$user)) {
                   10723:             ($group,my $file) = split(/\//,$file_name,2);
                   10724:         }
1.749     raeburn  10725:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10726:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10727:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10728:         #  remove lock
                   10729:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10730:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10731:         my $sqlresult =
1.970     raeburn  10732:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10733:                                     $group);
1.749     raeburn  10734:     } else {
                   10735:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10736:     }
1.749     raeburn  10737:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10738: }
                   10739: 
1.827     raeburn  10740: sub make_public_indefinitely {
                   10741:     my ($requrl) = @_;
                   10742:     my $now = time;
                   10743:     my $action = 'activate';
                   10744:     my $aclnum = 0;
                   10745:     if (&is_portfolio_url($requrl)) {
                   10746:         my (undef,$udom,$unum,$file_name,$group) =
                   10747:             &parse_portfolio_url($requrl);
                   10748:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10749:         my %access_controls = &get_access_controls($current_perms,
                   10750:                                                    $group,$file_name);
                   10751:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10752:             my ($num,$scope,$end,$start) = 
                   10753:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10754:             if ($scope eq 'public') {
                   10755:                 if ($start <= $now && $end == 0) {
                   10756:                     $action = 'none';
                   10757:                 } else {
                   10758:                     $action = 'update';
                   10759:                     $aclnum = $num;
                   10760:                 }
                   10761:                 last;
                   10762:             }
                   10763:         }
                   10764:         if ($action eq 'none') {
                   10765:              return 'ok';
                   10766:         } else {
                   10767:             my %changes;
                   10768:             my $newend = 0;
                   10769:             my $newstart = $now;
                   10770:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10771:             $changes{$action}{$newkey} = {
                   10772:                 type => 'public',
                   10773:                 time => {
                   10774:                     start => $newstart,
                   10775:                     end   => $newend,
                   10776:                 },
                   10777:             };
                   10778:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10779:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10780:             return $outcome;
                   10781:         }
                   10782:     } else {
                   10783:         return 'invalid';
                   10784:     }
                   10785: }
                   10786: 
1.745     raeburn  10787: #------------------------------------------------------Get Marked as Read Only
                   10788: 
                   10789: sub get_marked_as_readonly {
                   10790:     my ($domain,$user,$what,$group) = @_;
                   10791:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10792:     my @readonly_files;
1.629     banghart 10793:     my $cmp1=$what;
                   10794:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10795:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10796:         if (defined($group)) {
                   10797:             if ($file_name !~ m-^\Q$group\E/-) {
                   10798:                 next;
                   10799:             }
                   10800:         }
1.561     banghart 10801:         if (ref($value) eq "ARRAY"){
                   10802:             foreach my $stored_what (@{$value}) {
1.629     banghart 10803:                 my $cmp2=$stored_what;
1.759     albertel 10804:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10805:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10806:                 }
1.629     banghart 10807:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10808:                     push(@readonly_files, $file_name);
1.745     raeburn  10809:                     last;
1.563     banghart 10810:                 } elsif (!defined($what)) {
                   10811:                     push(@readonly_files, $file_name);
1.745     raeburn  10812:                     last;
1.561     banghart 10813:                 }
                   10814:             }
1.745     raeburn  10815:         }
1.561     banghart 10816:     }
                   10817:     return @readonly_files;
                   10818: }
1.577     banghart 10819: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10820: 
1.577     banghart 10821: sub get_marked_as_readonly_hash {
1.745     raeburn  10822:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10823:     my %readonly_files;
1.745     raeburn  10824:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10825:         if (defined($group)) {
                   10826:             if ($file_name !~ m-^\Q$group\E/-) {
                   10827:                 next;
                   10828:             }
                   10829:         }
1.577     banghart 10830:         if (ref($value) eq "ARRAY"){
                   10831:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10832:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10833:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10834:                         if ($lock_descriptor eq 'graded') {
                   10835:                             $readonly_files{$file_name} = 'graded';
                   10836:                         } elsif ($lock_descriptor eq 'handback') {
                   10837:                             $readonly_files{$file_name} = 'handback';
                   10838:                         } else {
                   10839:                             if (!exists($readonly_files{$file_name})) {
                   10840:                                 $readonly_files{$file_name} = 'locked';
                   10841:                             }
                   10842:                         }
1.745     raeburn  10843:                     }
1.750     banghart 10844:                 } 
1.577     banghart 10845:             }
                   10846:         } 
                   10847:     }
                   10848:     return %readonly_files;
                   10849: }
1.559     banghart 10850: # ------------------------------------------------------------ Unmark as Read Only
                   10851: 
                   10852: sub unmark_as_readonly {
1.629     banghart 10853:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10854:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10855:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10856:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10857:     my $symb_crs = $what;
                   10858:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10859:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10860:     my ($tmp)=keys(%current_permissions);
                   10861:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10862:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10863:     foreach my $file (@readonly_files) {
1.759     albertel 10864: 	my $clean_file = &declutter_portfile($file);
                   10865: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10866: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10867:         my @new_locks;
                   10868:         my @del_keys;
                   10869:         if (ref($current_locks) eq "ARRAY"){
                   10870:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10871:                 my $compare=$locker;
1.749     raeburn  10872:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10873:                     $compare=join('',@{$locker});
1.746     raeburn  10874:                     if ($compare ne $symb_crs) {
                   10875:                         push(@new_locks, $locker);
                   10876:                     }
1.563     banghart 10877:                 }
                   10878:             }
1.650     albertel 10879:             if (scalar(@new_locks) > 0) {
1.563     banghart 10880:                 $current_permissions{$file} = \@new_locks;
                   10881:             } else {
                   10882:                 push(@del_keys, $file);
1.613     albertel 10883:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10884:                 delete($current_permissions{$file});
1.563     banghart 10885:             }
                   10886:         }
1.561     banghart 10887:     }
1.613     albertel 10888:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10889:     return;
                   10890: }
1.512     banghart 10891: 
1.17      www      10892: # ------------------------------------------------------------ Directory lister
                   10893: 
                   10894: sub dirlist {
1.955     raeburn  10895:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10896:     $uri=~s/^\///;
                   10897:     $uri=~s/\/$//;
1.253     stredwic 10898:     my ($udom, $uname);
1.955     raeburn  10899:     if ($getuserdir) {
1.253     stredwic 10900:         $udom = $userdomain;
                   10901:         $uname = $username;
1.955     raeburn  10902:     } else {
                   10903:         (undef,$udom,$uname)=split(/\//,$uri);
                   10904:         if(defined($userdomain)) {
                   10905:             $udom = $userdomain;
                   10906:         }
                   10907:         if(defined($username)) {
                   10908:             $uname = $username;
                   10909:         }
1.253     stredwic 10910:     }
1.955     raeburn  10911:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10912: 
1.955     raeburn  10913:     $dirRoot = $perlvar{'lonDocRoot'};
                   10914:     if (defined($getpropath)) {
                   10915:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10916:         $dirRoot =~ s/\/$//;
1.955     raeburn  10917:     } elsif (defined($getuserdir)) {
                   10918:         my $subdir=$uname.'__';
                   10919:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10920:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10921:                    ."/$udom/$subdir/$uname";
                   10922:     } elsif (defined($alternateRoot)) {
                   10923:         $dirRoot = $alternateRoot;
1.751     banghart 10924:     }
1.253     stredwic 10925: 
                   10926:     if($udom) {
                   10927:         if($uname) {
1.1135    raeburn  10928:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10929:             if ($uhome eq 'no_host') {
                   10930:                 return ([],'no_host');
                   10931:             }
1.955     raeburn  10932:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10933:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10934:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10935:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10936:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10937:             } else {
                   10938:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10939:             }
1.605     matthew  10940:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10941:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10942:                 @listing_results = split(/:/,$listing);
                   10943:             } else {
                   10944:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10945:             }
1.1135    raeburn  10946:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10947:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10948:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10949:                 return ([],$listing);
                   10950:             } else {
                   10951:                 return (\@listing_results);
1.1135    raeburn  10952:             }
1.955     raeburn  10953:         } elsif(!$alternateRoot) {
1.1136    raeburn  10954:             my (%allusers,%listerror);
1.841     albertel 10955: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10956:  	    foreach my $tryserver (keys(%servers)) {
                   10957:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10958:                                   &escape($udom),$tryserver);
                   10959:                 if ($listing eq 'unknown_cmd') {
                   10960: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10961: 				      $udom, $tryserver);
                   10962:                 } else {
                   10963:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10964:                 }
1.841     albertel 10965: 		if ($listing eq 'unknown_cmd') {
                   10966: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10967: 				      $udom, $tryserver);
                   10968: 		    @listing_results = split(/:/,$listing);
                   10969: 		} else {
                   10970: 		    @listing_results =
                   10971: 			map { &unescape($_); } split(/:/,$listing);
                   10972: 		}
1.1136    raeburn  10973:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10974:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10975:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10976:                     $listerror{$tryserver} = $listing;
                   10977:                 } else {
1.841     albertel 10978: 		    foreach my $line (@listing_results) {
                   10979: 			my ($entry) = split(/&/,$line,2);
                   10980: 			$allusers{$entry} = 1;
                   10981: 		    }
                   10982: 		}
1.253     stredwic 10983:             }
1.1136    raeburn  10984:             my @alluserslist=();
1.800     albertel 10985:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10986:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10987:             }
1.1172.2.80  raeburn  10988:             if (!%listerror) {
                   10989:                 # no errors
                   10990:                 return (\@alluserslist);
                   10991:             } elsif (scalar(keys(%servers)) == 1) {
                   10992:                 # one library server, one error
                   10993:                 my ($key) = keys(%listerror);
                   10994:                 return (\@alluserslist, $listerror{$key});
                   10995:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10996:                 # con_lost indicates that we might miss data from at least one
                   10997:                 # library server
                   10998:                 return (\@alluserslist, 'con_lost');
                   10999:             } else {
                   11000:                 # multiple library servers and no con_lost -> data should be
                   11001:                 # complete.
                   11002:                 return (\@alluserslist);
                   11003:             }
                   11004: 
1.253     stredwic 11005:         } else {
1.1136    raeburn  11006:             return ([],'missing username');
1.253     stredwic 11007:         }
1.955     raeburn  11008:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11009:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11010:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11011:         return (\@all_domains);
1.955     raeburn  11012:     } else {
1.1136    raeburn  11013:         return ([],'missing domain');
1.275     stredwic 11014:     }
                   11015: }
                   11016: 
                   11017: # --------------------------------------------- GetFileTimestamp
                   11018: # This function utilizes dirlist and returns the date stamp for
                   11019: # when it was last modified.  It will also return an error of -1
                   11020: # if an error occurs
                   11021: 
                   11022: sub GetFileTimestamp {
1.955     raeburn  11023:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11024:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11025:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11026:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11027:                                     undef,$getuserdir);
                   11028:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11029:         return -1;
                   11030:     }
                   11031:     if (ref($fileref) eq 'ARRAY') {
                   11032:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11033:         # @stats contains first the filename, then the stat output
                   11034:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11035:     } else {
                   11036:         return -1;
1.253     stredwic 11037:     }
1.26      www      11038: }
                   11039: 
1.712     albertel 11040: sub stat_file {
                   11041:     my ($uri) = @_;
1.787     albertel 11042:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11043: 
1.955     raeburn  11044:     my ($udom,$uname,$file);
1.712     albertel 11045:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11046: 	($udom,$uname,$file) =
1.811     albertel 11047: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11048: 	$file = 'userfiles/'.$file;
                   11049:     }
                   11050:     if ($uri =~ m-^/res/-) {
                   11051: 	($udom,$uname) = 
1.807     albertel 11052: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11053: 	$file = $uri;
                   11054:     }
                   11055: 
                   11056:     if (!$udom || !$uname || !$file) {
                   11057: 	# unable to handle the uri
                   11058: 	return ();
                   11059:     }
1.956     raeburn  11060:     my $getpropath;
                   11061:     if ($file =~ /^userfiles\//) {
                   11062:         $getpropath = 1;
                   11063:     }
1.1136    raeburn  11064:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11065:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11066:         return ();
                   11067:     } else {
                   11068:         if (ref($listref) eq 'ARRAY') {
                   11069:             my @stats = split('&',$listref->[0]);
                   11070: 	    shift(@stats); #filename is first
                   11071: 	    return @stats;
                   11072:         }
1.712     albertel 11073:     }
                   11074:     return ();
                   11075: }
                   11076: 
1.26      www      11077: # -------------------------------------------------------- Value of a Condition
                   11078: 
1.713     albertel 11079: # gets the value of a specific preevaluated condition
                   11080: #    stored in the string  $env{user.state.<cid>}
                   11081: # or looks up a condition reference in the bighash and if if hasn't
                   11082: # already been evaluated recurses into docondval to get the value of
                   11083: # the condition, then memoizing it to 
                   11084: #   $env{user.state.<cid>.<condition>}
1.40      www      11085: sub directcondval {
                   11086:     my $number=shift;
1.620     albertel 11087:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11088: 	&Apache::lonuserstate::evalstate();
                   11089:     }
1.713     albertel 11090:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11091: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11092:     } elsif ($number =~ /^_/) {
                   11093: 	my $sub_condition;
                   11094: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11095: 		&GDBM_READER(),0640)) {
                   11096: 	    $sub_condition=$bighash{'conditions'.$number};
                   11097: 	    untie(%bighash);
                   11098: 	}
                   11099: 	my $value = &docondval($sub_condition);
1.949     raeburn  11100: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11101: 	return $value;
                   11102:     }
1.620     albertel 11103:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11104:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11105:     } else {
                   11106:        return 2;
                   11107:     }
                   11108: }
                   11109: 
1.713     albertel 11110: # get the collection of conditions for this resource
1.26      www      11111: sub condval {
                   11112:     my $condidx=shift;
1.54      www      11113:     my $allpathcond='';
1.713     albertel 11114:     foreach my $cond (split(/\|/,$condidx)) {
                   11115: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11116: 	    $allpathcond.=
                   11117: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11118: 	}
1.191     harris41 11119:     }
1.54      www      11120:     $allpathcond=~s/\|$//;
1.713     albertel 11121:     return &docondval($allpathcond);
                   11122: }
                   11123: 
                   11124: #evaluates an expression of conditions
                   11125: sub docondval {
                   11126:     my ($allpathcond) = @_;
                   11127:     my $result=0;
                   11128:     if ($env{'request.course.id'}
                   11129: 	&& defined($allpathcond)) {
                   11130: 	my $operand='|';
                   11131: 	my @stack;
                   11132: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11133: 	    if ($chunk eq '(') {
                   11134: 		push @stack,($operand,$result);
                   11135: 	    } elsif ($chunk eq ')') {
                   11136: 		my $before=pop @stack;
                   11137: 		if (pop @stack eq '&') {
                   11138: 		    $result=$result>$before?$before:$result;
                   11139: 		} else {
                   11140: 		    $result=$result>$before?$result:$before;
                   11141: 		}
                   11142: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11143: 		$operand=$chunk;
                   11144: 	    } else {
                   11145: 		my $new=directcondval($chunk);
                   11146: 		if ($operand eq '&') {
                   11147: 		    $result=$result>$new?$new:$result;
                   11148: 		} else {
                   11149: 		    $result=$result>$new?$result:$new;
                   11150: 		}
                   11151: 	    }
                   11152: 	}
1.26      www      11153:     }
                   11154:     return $result;
1.421     albertel 11155: }
                   11156: 
                   11157: # ---------------------------------------------------- Devalidate courseresdata
                   11158: 
                   11159: sub devalidatecourseresdata {
                   11160:     my ($coursenum,$coursedomain)=@_;
                   11161:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11162:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11163: }
                   11164: 
1.763     www      11165: 
1.200     www      11166: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11167: #
                   11168: #  Parameters:
                   11169: #      $coursenum    - Number of the course.
                   11170: #      $coursedomain - Domain at which the course was created.
                   11171: #  Returns:
                   11172: #     A hash of the course parameters along (I think) with timestamps
                   11173: #     and version info.
1.877     foxr     11174: 
1.624     albertel 11175: sub get_courseresdata {
                   11176:     my ($coursenum,$coursedomain)=@_;
1.200     www      11177:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11178:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11179:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11180:     my %dumpreply;
1.417     albertel 11181:     unless (defined($cached)) {
1.624     albertel 11182: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11183: 	$result=\%dumpreply;
1.251     albertel 11184: 	my ($tmp) = keys(%dumpreply);
                   11185: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11186: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11187: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11188: 	    return $tmp;
1.416     albertel 11189: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11190: 	    $result=undef;
1.599     albertel 11191: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11192: 	}
                   11193:     }
1.624     albertel 11194:     return $result;
                   11195: }
                   11196: 
1.633     albertel 11197: sub devalidateuserresdata {
                   11198:     my ($uname,$udom)=@_;
                   11199:     my $hashid="$udom:$uname";
                   11200:     &devalidate_cache_new('userres',$hashid);
                   11201: }
                   11202: 
1.624     albertel 11203: sub get_userresdata {
                   11204:     my ($uname,$udom)=@_;
                   11205:     #most student don\'t have any data set, check if there is some data
                   11206:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11207: 
                   11208:     my $hashid="$udom:$uname";
                   11209:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11210:     if (!defined($cached)) {
                   11211: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11212: 	$result=\%resourcedata;
                   11213: 	&do_cache_new('userres',$hashid,$result,600);
                   11214:     }
                   11215:     my ($tmp)=keys(%$result);
                   11216:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11217: 	return $result;
                   11218:     }
                   11219:     #error 2 occurs when the .db doesn't exist
                   11220:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11221:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11222: 	    &logthis("<font color=\"blue\">WARNING:".
                   11223: 		     " Trying to get resource data for ".
                   11224: 		     $uname." at ".$udom.": ".
                   11225: 		     $tmp."</font>");
                   11226:         }
1.624     albertel 11227:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11228: 	#&EXT_cache_set($udom,$uname);
                   11229: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11230: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11231:     }
                   11232:     return $tmp;
                   11233: }
1.879     foxr     11234: #----------------------------------------------- resdata - return resource data
                   11235: #  Purpose:
                   11236: #    Return resource data for either users or for a course.
                   11237: #  Parameters:
                   11238: #     $name      - Course/user name.
                   11239: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11240:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11241: #     @which     - Array of names of resources desired.
                   11242: #  Returns:
                   11243: #     The value of the first reasource in @which that is found in the
                   11244: #     resource hash.
                   11245: #  Exceptional Conditions:
                   11246: #     If the $type passed in is not valid (not the string 'course' or 
                   11247: #     'user', an undefined  reference is returned.
                   11248: #     If none of the resources are found, an undef is returned
1.624     albertel 11249: sub resdata {
                   11250:     my ($name,$domain,$type,@which)=@_;
                   11251:     my $result;
                   11252:     if ($type eq 'course') {
                   11253: 	$result=&get_courseresdata($name,$domain);
                   11254:     } elsif ($type eq 'user') {
                   11255: 	$result=&get_userresdata($name,$domain);
                   11256:     }
                   11257:     if (!ref($result)) { return $result; }    
1.251     albertel 11258:     foreach my $item (@which) {
1.1172.2.118.  .1(raebu 11259:20):         if (ref($item) eq 'ARRAY') {
                   11260:20): 	    if (defined($result->{$item->[0]})) {
                   11261:20): 	        return [$result->{$item->[0]},$item->[1]];
                   11262:20): 	    }
                   11263:20):         }
1.250     albertel 11264:     }
1.291     albertel 11265:     return undef;
1.200     www      11266: }
                   11267: 
1.1172.2.118.  .1(raebu 11268:20): sub get_domain_ltitools {
                   11269:20):     my ($cdom) = @_;
                   11270:20):     my %ltitools;
                   11271:20):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11272:20):     if (defined($cached)) {
                   11273:20):         if (ref($result) eq 'HASH') {
                   11274:20):             %ltitools = %{$result};
                   11275:20):         }
                   11276:20):     } else {
                   11277:20):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11278:20):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11279:20):             %ltitools = %{$domconfig{'ltitools'}};
                   11280:20):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11281:20):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11282:20):                 foreach my $id (keys(%ltitools)) {
                   11283:20):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11284:20):                         foreach my $item ('key','secret') {
                   11285:20):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11286:20):                         }
                   11287:20):                     }
                   11288:20):                 }
                   11289:20):             }
                   11290:20):         }
                   11291:20):         my $cachetime = 24*60*60;
                   11292:20):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11293:20):     }
                   11294:20):     return %ltitools;
                   11295:20): }
                   11296:20): 
1.1172.2.31  raeburn  11297: sub get_numsuppfiles {
                   11298:     my ($cnum,$cdom,$ignorecache)=@_;
                   11299:     my $hashid=$cnum.':'.$cdom;
                   11300:     my ($suppcount,$cached);
                   11301:     unless ($ignorecache) {
                   11302:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11303:     }
                   11304:     unless (defined($cached)) {
                   11305:         my $chome=&homeserver($cnum,$cdom);
                   11306:         unless ($chome eq 'no_host') {
                   11307:             ($suppcount,my $errors) = (0,0);
                   11308:             my $suppmap = 'supplemental.sequence';
                   11309:             ($suppcount,$errors) =
                   11310:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11311:         }
                   11312:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11313:     }
                   11314:     return $suppcount;
                   11315: }
                   11316: 
1.379     matthew  11317: #
                   11318: # EXT resource caching routines
                   11319: #
                   11320: 
                   11321: sub clear_EXT_cache_status {
1.383     albertel 11322:     &delenv('cache.EXT.');
1.379     matthew  11323: }
                   11324: 
                   11325: sub EXT_cache_status {
                   11326:     my ($target_domain,$target_user) = @_;
1.383     albertel 11327:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11328:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11329:         # We know already the user has no data
                   11330:         return 1;
                   11331:     } else {
                   11332:         return 0;
                   11333:     }
                   11334: }
                   11335: 
                   11336: sub EXT_cache_set {
                   11337:     my ($target_domain,$target_user) = @_;
1.383     albertel 11338:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11339:     #&appenv({$cachename => time});
1.379     matthew  11340: }
                   11341: 
1.28      www      11342: # --------------------------------------------------------- Value of a Variable
1.58      www      11343: sub EXT {
1.715     albertel 11344: 
1.1172.2.28  raeburn  11345:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11346:     unless ($varname) { return ''; }
1.218     albertel 11347:     #get real user name/domain, courseid and symb
                   11348:     my $courseid;
1.359     albertel 11349:     my $publicuser;
1.427     www      11350:     if ($symbparm) {
                   11351: 	$symbparm=&get_symb_from_alias($symbparm);
                   11352:     }
1.218     albertel 11353:     if (!($uname && $udom)) {
1.790     albertel 11354:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11355:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11356:     } else {
1.620     albertel 11357: 	$courseid=$env{'request.course.id'};
1.218     albertel 11358:     }
1.48      www      11359:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11360:     my $rest;
1.320     albertel 11361:     if (defined($therest[0])) {
1.48      www      11362:        $rest=join('.',@therest);
                   11363:     } else {
                   11364:        $rest='';
                   11365:     }
1.320     albertel 11366: 
1.57      www      11367:     my $qualifierrest=$qualifier;
                   11368:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11369:     my $spacequalifierrest=$space;
                   11370:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11371:     if ($realm eq 'user') {
1.48      www      11372: # --------------------------------------------------------------- user.resource
                   11373: 	if ($space eq 'resource') {
1.651     albertel 11374: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11375: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11376: 		 &&
1.744     albertel 11377: 		 ($symbparm eq &symbread()) ) {	
                   11378: 		# if we are in the middle of processing the resource the
                   11379: 		# get the value we are planning on committing
                   11380:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11381:                     return $Apache::lonhomework::results{$qualifierrest};
                   11382:                 } else {
                   11383:                     return $Apache::lonhomework::history{$qualifierrest};
                   11384:                 }
1.335     albertel 11385: 	    } else {
1.359     albertel 11386: 		my %restored;
1.620     albertel 11387: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11388: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11389: 		} else {
                   11390: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11391: 		}
1.335     albertel 11392: 		return $restored{$qualifierrest};
                   11393: 	    }
1.48      www      11394: # ----------------------------------------------------------------- user.access
                   11395:         } elsif ($space eq 'access') {
1.218     albertel 11396: 	    # FIXME - not supporting calls for a specific user
1.48      www      11397:             return &allowed($qualifier,$rest);
                   11398: # ------------------------------------------ user.preferences, user.environment
                   11399:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11400: 	    if (($uname eq $env{'user.name'}) &&
                   11401: 		($udom eq $env{'user.domain'})) {
                   11402: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11403: 	    } else {
1.359     albertel 11404: 		my %returnhash;
                   11405: 		if (!$publicuser) {
                   11406: 		    %returnhash=&userenvironment($udom,$uname,
                   11407: 						 $qualifierrest);
                   11408: 		}
1.218     albertel 11409: 		return $returnhash{$qualifierrest};
                   11410: 	    }
1.48      www      11411: # ----------------------------------------------------------------- user.course
                   11412:         } elsif ($space eq 'course') {
1.218     albertel 11413: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11414:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11415: # ------------------------------------------------------------------- user.role
                   11416:         } elsif ($space eq 'role') {
1.218     albertel 11417: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11418:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11419:             if ($qualifier eq 'value') {
                   11420: 		return $role;
                   11421:             } elsif ($qualifier eq 'extent') {
                   11422:                 return $where;
                   11423:             }
                   11424: # ----------------------------------------------------------------- user.domain
                   11425:         } elsif ($space eq 'domain') {
1.218     albertel 11426:             return $udom;
1.48      www      11427: # ------------------------------------------------------------------- user.name
                   11428:         } elsif ($space eq 'name') {
1.218     albertel 11429:             return $uname;
1.48      www      11430: # ---------------------------------------------------- Any other user namespace
1.29      www      11431:         } else {
1.359     albertel 11432: 	    my %reply;
                   11433: 	    if (!$publicuser) {
                   11434: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11435: 	    }
                   11436: 	    return $reply{$qualifierrest};
1.48      www      11437:         }
1.236     www      11438:     } elsif ($realm eq 'query') {
                   11439: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11440:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11441: 						[$spacequalifierrest]);
1.620     albertel 11442: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11443:    } elsif ($realm eq 'request') {
1.48      www      11444: # ------------------------------------------------------------- request.browser
                   11445:         if ($space eq 'browser') {
1.1145    bisitz   11446:             return $env{'browser.'.$qualifier};
1.57      www      11447: # ------------------------------------------------------------ request.filename
                   11448:         } else {
1.620     albertel 11449:             return $env{'request.'.$spacequalifierrest};
1.29      www      11450:         }
1.28      www      11451:     } elsif ($realm eq 'course') {
1.48      www      11452: # ---------------------------------------------------------- course.description
1.620     albertel 11453:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11454:     } elsif ($realm eq 'resource') {
1.165     www      11455: 
1.620     albertel 11456: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11457: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11458: 	}
1.693     albertel 11459: 
1.1172.2.30  raeburn  11460:         if ($qualifier eq '') {
                   11461: 	    if ($space eq 'title') {
                   11462: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11463: 	        return &gettitle($symbparm);
                   11464: 	    }
1.693     albertel 11465: 	
1.1172.2.30  raeburn  11466: 	    if ($space eq 'map') {
                   11467: 	        my ($map) = &decode_symb($symbparm);
                   11468: 	        return &symbread($map);
                   11469: 	    }
                   11470:             if ($space eq 'maptitle') {
                   11471:                 my ($map) = &decode_symb($symbparm);
                   11472:                 return &gettitle($map);
                   11473:             }
                   11474: 	    if ($space eq 'filename') {
                   11475: 	        if ($symbparm) {
                   11476: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11477: 	        }
                   11478: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11479: 	    }
1.1172.2.30  raeburn  11480: 
                   11481:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11482:                 if ($space eq 'visibleparts') {
                   11483:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11484:                     my $item;
                   11485:                     if (ref($navmap)) {
                   11486:                         my $res = $navmap->getBySymb($symbparm);
                   11487:                         my $parts = $res->parts();
                   11488:                         if (ref($parts) eq 'ARRAY') {
                   11489:                             $item = join(',',@{$parts});
                   11490:                         }
                   11491:                         undef($navmap);
                   11492:                     }
                   11493:                     return $item;
                   11494:                 }
                   11495:             }
                   11496:         }
1.693     albertel 11497: 
                   11498: 	my ($section, $group, @groups);
1.593     albertel 11499: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11500:         if (($courseid eq '') && ($cid)) {
                   11501:             $courseid = $cid;
                   11502:         }
                   11503: 	if (($symbparm && $courseid) && 
                   11504: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11505: 
1.218     albertel 11506: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11507: 
1.60      www      11508: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11509: 	    my $symbp=$symbparm;
1.735     albertel 11510: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11511: 
                   11512: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11513: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11514: 
1.620     albertel 11515: 	    if (($env{'user.name'} eq $uname) &&
                   11516: 		($env{'user.domain'} eq $udom)) {
                   11517: 		$section=$env{'request.course.sec'};
1.733     raeburn  11518:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11519:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11520: 	    } else {
1.539     albertel 11521: 		if (! defined($usection)) {
1.551     albertel 11522: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11523: 		} else {
                   11524: 		    $section = $usection;
                   11525: 		}
1.733     raeburn  11526:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11527: 	    }
                   11528: 
                   11529: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11530: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11531: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11532: 
1.593     albertel 11533: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11534: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11535: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11536: 
1.60      www      11537: # ----------------------------------------------------------- first, check user
1.624     albertel 11538: 
                   11539: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11540: 				       ([$courselevelr,'resource'],
                   11541: 					[$courselevelm,'map'     ],
                   11542: 					[$courselevel, 'course'  ]));
1.931     albertel 11543: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11544: 
1.594     albertel 11545: # ------------------------------------------------ second, check some of course
1.684     raeburn  11546:             my $coursereply;
1.691     raeburn  11547:             if (@groups > 0) {
                   11548:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11549:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11550:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11551:             }
1.96      www      11552: 
1.684     raeburn  11553: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11554: 				  $env{'course.'.$courseid.'.domain'},
                   11555: 				  'course',
                   11556: 				  ([$seclevelr,   'resource'],
                   11557: 				   [$seclevelm,   'map'     ],
                   11558: 				   [$seclevel,    'course'  ],
                   11559: 				   [$courselevelr,'resource']));
                   11560: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11561: 
1.60      www      11562: # ------------------------------------------------------ third, check map parms
1.218     albertel 11563: 	    my %parmhash=();
                   11564: 	    my $thisparm='';
                   11565: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11566: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11567: 		    &GDBM_READER(),0640)) {
1.218     albertel 11568: 		$thisparm=$parmhash{$symbparm};
                   11569: 		untie(%parmhash);
                   11570: 	    }
1.927     albertel 11571: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11572: 	}
1.594     albertel 11573: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11574: 
1.218     albertel 11575: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11576: 	my $filename;
                   11577: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11578: 	if ($symbparm) {
1.409     www      11579: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11580: 	} else {
1.620     albertel 11581: 	    $filename=$env{'request.filename'};
1.282     albertel 11582: 	}
                   11583: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11584: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11585: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11586: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11587: 
1.927     albertel 11588: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11589: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11590: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11591: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11592: 				     $env{'course.'.$courseid.'.domain'},
                   11593: 				     'course',
1.927     albertel 11594: 				     ([$courselevelm,'map'   ],
                   11595: 				      [$courselevel, 'course']));
                   11596: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11597: 	}
1.145     www      11598: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11599: 	unless ($space eq '0') {
1.336     albertel 11600: 	    my @parts=split(/_/,$space);
                   11601: 	    my $id=pop(@parts);
                   11602: 	    my $part=join('_',@parts);
                   11603: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11604: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11605: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11606: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11607: 	}
1.395     albertel 11608: 	if ($recurse) { return undef; }
                   11609: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11610: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11611: # ---------------------------------------------------- Any other user namespace
                   11612:     } elsif ($realm eq 'environment') {
                   11613: # ----------------------------------------------------------------- environment
1.620     albertel 11614: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11615: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11616: 	} else {
1.770     albertel 11617: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11618: 		return '';
                   11619: 	    }
1.219     albertel 11620: 	    my %returnhash=&userenvironment($udom,$uname,
                   11621: 					    $spacequalifierrest);
                   11622: 	    return $returnhash{$spacequalifierrest};
                   11623: 	}
1.28      www      11624:     } elsif ($realm eq 'system') {
1.48      www      11625: # ----------------------------------------------------------------- system.time
                   11626: 	if ($space eq 'time') {
                   11627: 	    return time;
                   11628:         }
1.696     albertel 11629:     } elsif ($realm eq 'server') {
                   11630: # ----------------------------------------------------------------- system.time
                   11631: 	if ($space eq 'name') {
                   11632: 	    return $ENV{'SERVER_NAME'};
                   11633:         }
1.28      www      11634:     }
1.48      www      11635:     return '';
1.61      www      11636: }
                   11637: 
1.927     albertel 11638: sub get_reply {
                   11639:     my ($reply_value) = @_;
1.940     raeburn  11640:     if (ref($reply_value) eq 'ARRAY') {
                   11641:         if (wantarray) {
                   11642: 	    return @$reply_value;
                   11643:         }
                   11644:         return $reply_value->[0];
                   11645:     } else {
                   11646:         return $reply_value;
1.927     albertel 11647:     }
                   11648: }
                   11649: 
1.691     raeburn  11650: sub check_group_parms {
                   11651:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11652:     my @groupitems = ();
                   11653:     my $resultitem;
1.927     albertel 11654:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11655:     foreach my $group (@{$groups}) {
                   11656:         foreach my $level (@levels) {
1.927     albertel 11657:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11658:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11659:         }
                   11660:     }
                   11661:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11662:                             $env{'course.'.$courseid.'.domain'},
                   11663:                                      'course',@groupitems);
                   11664:     return $coursereply;
                   11665: }
                   11666: 
                   11667: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11668:     my ($courseid,@groups) = @_;
                   11669:     @groups = sort(@groups);
1.691     raeburn  11670:     return @groups;
                   11671: }
                   11672: 
1.395     albertel 11673: sub packages_tab_default {
                   11674:     my ($uri,$varname)=@_;
                   11675:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11676: 
                   11677:     my (@extension,@specifics,$do_default);
                   11678:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11679: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11680: 	if ($pack_type eq 'default') {
                   11681: 	    $do_default=1;
                   11682: 	} elsif ($pack_type eq 'extension') {
                   11683: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11684: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11685: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11686: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11687: 	}
                   11688:     }
                   11689:     # first look for a package that matches the requested part id
                   11690:     foreach my $package (@specifics) {
                   11691: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11692: 	next if ($pack_part ne $part);
                   11693: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11694: 	    return $packagetab{"$pack_type&$name&default"};
                   11695: 	}
                   11696:     }
                   11697:     # look for any possible matching non extension_ package
                   11698:     foreach my $package (@specifics) {
                   11699: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11700: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11701: 	    return $packagetab{"$pack_type&$name&default"};
                   11702: 	}
1.585     albertel 11703: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11704: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11705: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11706: 	}
                   11707:     }
1.738     albertel 11708:     # look for any posible extension_ match
                   11709:     foreach my $package (@extension) {
                   11710: 	my ($package,$pack_type)=@{$package};
                   11711: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11712: 	    return $packagetab{"$pack_type&$name&default"};
                   11713: 	}
                   11714: 	if (defined($packagetab{$package."&$name&default"})) {
                   11715: 	    return $packagetab{$package."&$name&default"};
                   11716: 	}
                   11717:     }
                   11718:     # look for a global default setting
                   11719:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11720: 	return $packagetab{"default&$name&default"};
                   11721:     }
1.395     albertel 11722:     return undef;
                   11723: }
                   11724: 
1.334     albertel 11725: sub add_prefix_and_part {
                   11726:     my ($prefix,$part)=@_;
                   11727:     my $keyroot;
                   11728:     if (defined($prefix) && $prefix !~ /^__/) {
                   11729: 	# prefix that has a part already
                   11730: 	$keyroot=$prefix;
                   11731:     } elsif (defined($prefix)) {
                   11732: 	# prefix that is missing a part
                   11733: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11734:     } else {
                   11735: 	# no prefix at all
                   11736: 	if (defined($part)) { $keyroot='_'.$part; }
                   11737:     }
                   11738:     return $keyroot;
                   11739: }
                   11740: 
1.71      www      11741: # ---------------------------------------------------------------- Get metadata
                   11742: 
1.599     albertel 11743: my %metaentry;
1.1070    www      11744: my %importedpartids;
1.1172.2.99  raeburn  11745: my %importedrespids;
1.71      www      11746: sub metadata {
1.176     www      11747:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11748:     $uri=&declutter($uri);
1.288     albertel 11749:     # if it is a non metadata possible uri return quickly
1.529     albertel 11750:     if (($uri eq '') || 
                   11751: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11752:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11753:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11754: 	return undef;
                   11755:     }
1.1172.2.49  raeburn  11756:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11757: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11758: 	return undef;
1.288     albertel 11759:     }
1.73      www      11760:     my $filename=$uri;
                   11761:     $uri=~s/\.meta$//;
1.172     www      11762: #
                   11763: # Is the metadata already cached?
1.177     www      11764: # Look at timestamp of caching
1.172     www      11765: # Everything is cached by the main uri, libraries are never directly cached
                   11766: #
1.428     albertel 11767:     if (!defined($liburi)) {
1.599     albertel 11768: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11769: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11770:     }
                   11771:     {
1.1069    www      11772: # Imported parts would go here
1.1172.2.99  raeburn  11773:         my @origfiletagids=();
1.1069    www      11774:         my $importedparts=0;
1.1172.2.99  raeburn  11775: 
                   11776: # Imported responseids would go here
                   11777:         my $importedresponses=0;
1.172     www      11778: #
                   11779: # Is this a recursive call for a library?
                   11780: #
1.599     albertel 11781: #	if (! exists($metacache{$uri})) {
                   11782: #	    $metacache{$uri}={};
                   11783: #	}
1.924     albertel 11784: 	my $cachetime = 60*60;
1.171     www      11785:         if ($liburi) {
                   11786: 	    $liburi=&declutter($liburi);
                   11787:             $filename=$liburi;
1.401     bowersj2 11788:         } else {
1.599     albertel 11789: 	    &devalidate_cache_new('meta',$uri);
                   11790: 	    undef(%metaentry);
1.401     bowersj2 11791: 	}
1.140     www      11792:         my %metathesekeys=();
1.73      www      11793:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11794: 	my $metastring;
1.1140    www      11795: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11796: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11797: 	    $metastring = 
1.929     albertel 11798: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11799: 					  ('grade_target' => 'meta'));
                   11800: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11801: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11802:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11803: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11804: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11805: 	    $metastring=&getfile($file);
1.489     albertel 11806: 	}
1.208     albertel 11807:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11808:         my $token;
1.140     www      11809:         undef %metathesekeys;
1.71      www      11810:         while ($token=$parser->get_token) {
1.339     albertel 11811: 	    if ($token->[0] eq 'S') {
                   11812: 		if (defined($token->[2]->{'package'})) {
1.172     www      11813: #
                   11814: # This is a package - get package info
                   11815: #
1.339     albertel 11816: 		    my $package=$token->[2]->{'package'};
                   11817: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11818: 		    if (defined($token->[2]->{'id'})) { 
                   11819: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11820: 		    }
1.599     albertel 11821: 		    if ($metaentry{':packages'}) {
                   11822: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11823: 		    } else {
1.599     albertel 11824: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11825: 		    }
1.736     albertel 11826: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11827: 			my $part=$keyroot;
                   11828: 			$part=~s/^\_//;
1.736     albertel 11829: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11830: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11831: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11832: 			    # ignore package.tab specified default values
                   11833:                             # here &package_tab_default() will fetch those
                   11834: 			    if ($subp eq 'default') { next; }
1.736     albertel 11835: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11836: 			    my $unikey;
                   11837: 			    if ($pack =~ /_0$/) {
                   11838: 				$unikey='parameter_0_'.$name;
                   11839: 				$part=0;
                   11840: 			    } else {
                   11841: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11842: 			    }
1.339     albertel 11843: 			    if ($subp eq 'display') {
                   11844: 				$value.=' [Part: '.$part.']';
                   11845: 			    }
1.599     albertel 11846: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11847: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11848: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11849: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11850: 			    }
1.599     albertel 11851: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11852: 				$metaentry{':'.$unikey}=
                   11853: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11854: 			    }
1.339     albertel 11855: 			}
                   11856: 		    }
                   11857: 		} else {
1.172     www      11858: #
                   11859: # This is not a package - some other kind of start tag
1.339     albertel 11860: #
                   11861: 		    my $entry=$token->[1];
1.1068    www      11862: 		    my $unikey='';
1.175     www      11863: 
1.339     albertel 11864: 		    if ($entry eq 'import') {
1.175     www      11865: #
                   11866: # Importing a library here
1.339     albertel 11867: #
1.1067    www      11868:                         my $location=$parser->get_text('/import');
                   11869:                         my $dir=$filename;
                   11870:                         $dir=~s|[^/]*$||;
                   11871:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11872: 
                   11873:                         my $importid=$token->[2]->{'id'};
1.1068    www      11874:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11875: #
                   11876: # Check metadata for imported file to
                   11877: # see if it contained response items
                   11878: #
                   11879:                         my %currmetaentry = %metaentry;
                   11880:                         my $libresponseorder = &metadata($location,'responseorder');
                   11881:                         my $origfile;
                   11882:                         if ($libresponseorder ne '') {
                   11883:                             if ($#origfiletagids<0) {
                   11884:                                 undef(%importedrespids);
                   11885:                                 undef(%importedpartids);
                   11886:                             }
                   11887:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11888:                             if (@{$importedrespids{$importid}} > 0) {
                   11889:                                 $importedresponses = 1;
                   11890: # We need to get the original file and the imported file to get the response order correct
                   11891: # Load and inspect original file
                   11892:                                 if ($#origfiletagids<0) {
                   11893:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11894:                                     $origfile=&getfile($origfilelocation);
                   11895:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11896:                                 }
                   11897:                             }
                   11898:                         }
                   11899: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11900: # hash populated for imported library file
                   11901:                         %metaentry = %currmetaentry;
                   11902:                         undef(%currmetaentry);
1.1068    www      11903:                         if ($importmode eq 'problem') {
1.1069    www      11904: # Import as problem/response
1.1068    www      11905:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11906:                         } elsif ($importmode eq 'part') {
                   11907: # Import as part(s)
1.1069    www      11908:                            $importedparts=1;
                   11909: # We need to get the original file and the imported file to get the part order correct
                   11910: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11911: # Load and inspect original file if we didn't do that already
                   11912:                            if ($#origfiletagids<0) {
                   11913:                                undef(%importedrespids);
                   11914:                                undef(%importedpartids);
                   11915:                                if ($origfile eq '') {
                   11916:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11917:                                    $origfile=&getfile($origfilelocation);
                   11918:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11919:                                }
1.1070    www      11920:                            }
                   11921: 
1.1069    www      11922: # Load and inspect imported file
                   11923:                            my $impfile=&getfile($location);
                   11924:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11925:                            if ($#impfilepartids>=0) {
                   11926: # This problem had parts
1.1070    www      11927:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11928:                            } else {
                   11929: # Importing by turning a single problem into a problem part
                   11930: # It gets the import-tags ID as part-ID
                   11931:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11932:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11933:                            }
1.1068    www      11934:                         } else {
                   11935: # Normal import
                   11936:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11937:                            if (defined($token->[2]->{'id'})) {
                   11938:                               $unikey.='_'.$token->[2]->{'id'};
                   11939:                            }
1.1067    www      11940:                         }
                   11941: 
1.339     albertel 11942: 			if ($depthcount<20) {
1.736     albertel 11943: 			    my $metadata = 
                   11944: 				&metadata($uri,'keys', $location,$unikey,
                   11945: 					  $depthcount+1);
                   11946: 			    foreach my $meta (split(',',$metadata)) {
                   11947: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11948: 				$metathesekeys{$meta}=1;
1.339     albertel 11949: 			    }
1.1068    www      11950: 			
                   11951:                         }
1.1067    www      11952: 		    } else {
                   11953: #
                   11954: # Not importing, some other kind of non-package, non-library start tag
                   11955: # 
                   11956:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11957:                         if (defined($token->[2]->{'id'})) {
                   11958:                             $unikey.='_'.$token->[2]->{'id'};
                   11959:                         }
1.339     albertel 11960: 			if (defined($token->[2]->{'name'})) { 
                   11961: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11962: 			}
                   11963: 			$metathesekeys{$unikey}=1;
1.736     albertel 11964: 			foreach my $param (@{$token->[3]}) {
                   11965: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11966: 				$token->[2]->{$param};
1.339     albertel 11967: 			}
                   11968: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11969: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11970: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11971: 		 # only ws inside the tag, and not in default, so use default
                   11972: 		 # as value
1.599     albertel 11973: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11974: 			} elsif ( $internaltext =~ /\S/ ) {
                   11975: 		  # something interesting inside the tag
                   11976: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11977: 			} else {
1.908     albertel 11978: 		  # no interesting values, don't set a default
1.339     albertel 11979: 			}
1.172     www      11980: # end of not-a-package not-a-library import
1.339     albertel 11981: 		    }
1.172     www      11982: # end of not-a-package start tag
1.339     albertel 11983: 		}
1.172     www      11984: # the next is the end of "start tag"
1.339     albertel 11985: 	    }
                   11986: 	}
1.483     albertel 11987: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11988: 	$extension = lc($extension);
                   11989: 	if ($extension eq 'htm') { $extension='html'; }
                   11990: 
1.737     albertel 11991: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11992: 	    #no specific packages #how's our extension
                   11993: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11994: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11995: 					 \%metathesekeys);
                   11996: 	}
1.883     albertel 11997: 
                   11998: 	if (!exists($metaentry{':packages'})
                   11999: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12000: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12001: 		#no specific packages well let's get default then
                   12002: 		if ($key!~/^default&/) { next; }
1.488     albertel 12003: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12004: 					     \%metathesekeys);
                   12005: 	    }
                   12006: 	}
1.338     www      12007: # are there custom rights to evaluate
1.599     albertel 12008: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12009: 
1.338     www      12010:     #
                   12011:     # Importing a rights file here
1.339     albertel 12012:     #
                   12013: 	    unless ($depthcount) {
1.599     albertel 12014: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12015: 		my $dir=$filename;
                   12016: 		$dir=~s|[^/]*$||;
                   12017: 		$location=&filelocation($dir,$location);
1.736     albertel 12018: 		my $rights_metadata =
                   12019: 		    &metadata($uri,'keys',$location,'_rights',
                   12020: 			      $depthcount+1);
                   12021: 		foreach my $rights (split(',',$rights_metadata)) {
                   12022: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12023: 		    $metathesekeys{$rights}=1;
1.339     albertel 12024: 		}
                   12025: 	    }
                   12026: 	}
1.737     albertel 12027: 	# uniqifiy package listing
                   12028: 	my %seen;
                   12029: 	my @uniq_packages =
                   12030: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12031: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12032: 
1.1172.2.99  raeburn  12033:         if (($importedresponses) || ($importedparts)) {
                   12034:             if ($importedparts) {
1.1070    www      12035: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12036:                 $metaentry{':partorder'}='';
                   12037:                 $metathesekeys{'partorder'}=1;
                   12038:             }
                   12039:             if ($importedresponses) {
                   12040: # We had imported responses and need to rebuild responseorder
                   12041:                 $metaentry{':responseorder'}='';
                   12042:                 $metathesekeys{'responseorder'}=1;
                   12043:             }
                   12044:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12045:                 my $origid = $origfiletagids[$index+1];
                   12046:                 if ($origfiletagids[$index] eq 'part') {
                   12047: # Original part, part of the problem
                   12048:                     if ($importedparts) {
                   12049:                         $metaentry{':partorder'}.=','.$origid;
                   12050:                     }
                   12051:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12052:                     if ($importedparts) {
                   12053: # We have imported parts at this position
                   12054:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12055:                     }
                   12056:                     if ($importedresponses) {
                   12057: # We have imported responses at this position
                   12058:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12059:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12060:                         }
                   12061:                     }
                   12062:                 } else {
                   12063: # Original response item, part of the problem
                   12064:                     if ($importedresponses) {
                   12065:                         $metaentry{':responseorder'}.=','.$origid;
                   12066:                     }
                   12067:                 }
                   12068:             }
                   12069:             if ($importedparts) {
                   12070:                 $metaentry{':partorder'}=~s/^\,//;
                   12071:             }
                   12072:             if ($importedresponses) {
                   12073:                 $metaentry{':responseorder'}=~s/^\,//;
                   12074:             }
1.1070    www      12075:         }
                   12076: 
1.737     albertel 12077: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12078: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12079: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12080: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12081: # this is the end of "was not already recently cached
1.71      www      12082:     }
1.599     albertel 12083:     return $metaentry{':'.$what};
1.261     albertel 12084: }
                   12085: 
1.488     albertel 12086: sub metadata_create_package_def {
1.483     albertel 12087:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12088:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12089:     if ($subp eq 'default') { next; }
                   12090:     
1.599     albertel 12091:     if (defined($metaentry{':packages'})) {
                   12092: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12093:     } else {
1.599     albertel 12094: 	$metaentry{':packages'}=$package;
1.483     albertel 12095:     }
                   12096:     my $value=$packagetab{$key};
                   12097:     my $unikey;
                   12098:     $unikey='parameter_0_'.$name;
1.599     albertel 12099:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12100:     $$metathesekeys{$unikey}=1;
1.599     albertel 12101:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12102: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12103:     }
1.599     albertel 12104:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12105: 	$metaentry{':'.$unikey}=
                   12106: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12107:     }
                   12108: }
                   12109: 
1.261     albertel 12110: sub metadata_generate_part0 {
                   12111:     my ($metadata,$metacache,$uri) = @_;
                   12112:     my %allnames;
1.737     albertel 12113:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12114: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12115: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12116: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12117: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12118: 	    $allnames{$name}=$part;
                   12119: 	  }
                   12120: 	}
                   12121:     }
                   12122:     foreach my $name (keys(%allnames)) {
                   12123:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12124:       my $key=":parameter_0_$name";
1.261     albertel 12125:       $$metacache{"$key.part"}='0';
                   12126:       $$metacache{"$key.name"}=$name;
1.428     albertel 12127:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12128: 					   $allnames{$name}.'_'.$name.
                   12129: 					   '.type'};
1.428     albertel 12130:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12131: 			     '.display'};
1.644     www      12132:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12133:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12134:       $$metacache{"$key.display"}=$olddis;
                   12135:     }
1.71      www      12136: }
                   12137: 
1.764     albertel 12138: # ------------------------------------------------------ Devalidate title cache
                   12139: 
                   12140: sub devalidate_title_cache {
                   12141:     my ($url)=@_;
                   12142:     if (!$env{'request.course.id'}) { return; }
                   12143:     my $symb=&symbread($url);
                   12144:     if (!$symb) { return; }
                   12145:     my $key=$env{'request.course.id'}."\0".$symb;
                   12146:     &devalidate_cache_new('title',$key);
                   12147: }
                   12148: 
1.1014    droeschl 12149: # ------------------------------------------------- Get the title of a course
                   12150: 
                   12151: sub current_course_title {
                   12152:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12153: }
1.301     www      12154: # ------------------------------------------------- Get the title of a resource
                   12155: 
                   12156: sub gettitle {
                   12157:     my $urlsymb=shift;
                   12158:     my $symb=&symbread($urlsymb);
1.534     albertel 12159:     if ($symb) {
1.620     albertel 12160: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12161: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12162: 	if (defined($cached)) { 
                   12163: 	    return $result;
                   12164: 	}
1.534     albertel 12165: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12166: 	my $title='';
1.907     albertel 12167: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12168: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12169: 	} else {
                   12170: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12171: 		    &GDBM_READER(),0640)) {
                   12172: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12173: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12174: 		untie(%bighash);
                   12175: 	    }
1.534     albertel 12176: 	}
                   12177: 	$title=~s/\&colon\;/\:/gs;
                   12178: 	if ($title) {
1.1159    www      12179: # Remember both $symb and $title for dynamic metadata
                   12180:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12181:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12182: # Cache this title and then return it
1.599     albertel 12183: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12184: 	}
                   12185: 	$urlsymb=$url;
                   12186:     }
                   12187:     my $title=&metadata($urlsymb,'title');
                   12188:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12189:     return $title;
1.301     www      12190: }
1.613     albertel 12191: 
1.614     albertel 12192: sub get_slot {
                   12193:     my ($which,$cnum,$cdom)=@_;
                   12194:     if (!$cnum || !$cdom) {
1.790     albertel 12195: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12196: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12197: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12198:     }
1.703     albertel 12199:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12200:     my %slotinfo;
                   12201:     if (exists($remembered{$key})) {
                   12202: 	$slotinfo{$which} = $remembered{$key};
                   12203:     } else {
                   12204: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12205: 	&Apache::lonhomework::showhash(%slotinfo);
                   12206: 	my ($tmp)=keys(%slotinfo);
                   12207: 	if ($tmp=~/^error:/) { return (); }
                   12208: 	$remembered{$key} = $slotinfo{$which};
                   12209:     }
1.616     albertel 12210:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12211: 	return %{$slotinfo{$which}};
                   12212:     }
                   12213:     return $slotinfo{$which};
1.614     albertel 12214: }
1.1150    raeburn  12215: 
                   12216: sub get_reservable_slots {
                   12217:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12218:     my $now = time;
                   12219:     my $reservable_info;
                   12220:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12221:     if (exists($remembered{$key})) {
                   12222:         $reservable_info = $remembered{$key};
                   12223:     } else {
                   12224:         my %resv;
                   12225:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12226:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12227:         $reservable_info = \%resv;
                   12228:         $remembered{$key} = $reservable_info;
                   12229:     }
                   12230:     return $reservable_info;
                   12231: }
                   12232: 
                   12233: sub get_course_slots {
                   12234:     my ($cnum,$cdom) = @_;
                   12235:     my $hashid=$cnum.':'.$cdom;
                   12236:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12237:     if (defined($cached)) {
                   12238:         if (ref($result) eq 'HASH') {
                   12239:             return %{$result};
                   12240:         }
                   12241:     } else {
                   12242:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12243:         my ($tmp) = keys(%slots);
                   12244:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12245:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12246:             return %slots;
                   12247:         }
                   12248:     }
                   12249:     return;
                   12250: }
                   12251: 
                   12252: sub devalidate_slots_cache {
                   12253:     my ($cnum,$cdom)=@_;
                   12254:     my $hashid=$cnum.':'.$cdom;
                   12255:     &devalidate_cache_new('allslots',$hashid);
                   12256: }
                   12257: 
1.1172.2.8  raeburn  12258: sub get_coursechange {
                   12259:     my ($cdom,$cnum) = @_;
                   12260:     if ($cdom eq '' || $cnum eq '') {
                   12261:         return unless ($env{'request.course.id'});
                   12262:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12263:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12264:     }
                   12265:     my $hashid=$cdom.'_'.$cnum;
                   12266:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12267:     if ((defined($cached)) && ($change ne '')) {
                   12268:         return $change;
                   12269:     } else {
                   12270:         my %crshash;
                   12271:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12272:         if ($crshash{'internal.contentchange'} eq '') {
                   12273:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12274:             if ($change eq '') {
                   12275:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12276:                 $change = $crshash{'internal.created'};
                   12277:             }
                   12278:         } else {
                   12279:             $change = $crshash{'internal.contentchange'};
                   12280:         }
                   12281:         my $cachetime = 600;
                   12282:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12283:     }
                   12284:     return $change;
                   12285: }
                   12286: 
                   12287: sub devalidate_coursechange_cache {
                   12288:     my ($cnum,$cdom)=@_;
                   12289:     my $hashid=$cnum.':'.$cdom;
                   12290:     &devalidate_cache_new('crschange',$hashid);
                   12291: }
                   12292: 
1.31      www      12293: # ------------------------------------------------- Update symbolic store links
                   12294: 
                   12295: sub symblist {
                   12296:     my ($mapname,%newhash)=@_;
1.438     www      12297:     $mapname=&deversion(&declutter($mapname));
1.31      www      12298:     my %hash;
1.620     albertel 12299:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12300:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12301:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12302: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12303: 		next if ($url eq 'last_known'
                   12304: 			 && $env{'form.no_update_last_known'});
                   12305: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12306: 						    $newhash{$url}->[1],
                   12307: 						    $newhash{$url}->[0]);
1.191     harris41 12308:             }
1.31      www      12309:             if (untie(%hash)) {
                   12310: 		return 'ok';
                   12311:             }
                   12312:         }
                   12313:     }
                   12314:     return 'error';
1.212     www      12315: }
                   12316: 
                   12317: # --------------------------------------------------------------- Verify a symb
                   12318: 
                   12319: sub symbverify {
1.1172.2.11  raeburn  12320:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12321:     my $thisfn=$thisurl;
1.439     www      12322:     $thisfn=&declutter($thisfn);
1.215     www      12323: # direct jump to resource in page or to a sequence - will construct own symbs
                   12324:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12325: # check URL part
1.409     www      12326:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12327: 
1.431     www      12328:     unless ($url eq $thisfn) { return 0; }
1.213     www      12329: 
1.216     www      12330:     $symb=&symbclean($symb);
1.510     www      12331:     $thisurl=&deversion($thisurl);
1.439     www      12332:     $thisfn=&deversion($thisfn);
1.213     www      12333: 
                   12334:     my %bighash;
                   12335:     my $okay=0;
1.431     www      12336: 
1.620     albertel 12337:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12338:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12339:         my $noclutter;
1.1032    raeburn  12340:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12341:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12342:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12343:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12344:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12345:                 $noclutter = 1;
                   12346:             }
                   12347:         }
                   12348:         my $ids;
                   12349:         if ($noclutter) {
                   12350:             $ids=$bighash{'ids_'.$thisurl};
                   12351:         } else {
                   12352:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12353:         }
1.1102    raeburn  12354:         unless ($ids) {
1.1172.2.13  raeburn  12355:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12356:             $ids=$bighash{$idkey};
1.216     www      12357:         }
                   12358:         if ($ids) {
                   12359: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12360:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12361:                 $symb =~ s/\?.+$//;
                   12362:             }
1.800     albertel 12363: 	    foreach my $id (split(/\,/,$ids)) {
                   12364: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12365:                if (
                   12366:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12367:    eq $symb) {
1.1172.2.11  raeburn  12368:                    if (ref($encstate)) {
                   12369:                        $$encstate = $bighash{'encrypted_'.$id};
                   12370:                    }
1.1172.2.13  raeburn  12371:                    if (($env{'request.role.adv'}) ||
                   12372:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12373:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12374:                        $okay=1;
                   12375:                        last;
                   12376:                    }
                   12377:                }
                   12378:            }
1.216     www      12379:         }
1.213     www      12380: 	untie(%bighash);
                   12381:     }
                   12382:     return $okay;
1.31      www      12383: }
                   12384: 
1.210     www      12385: # --------------------------------------------------------------- Clean-up symb
                   12386: 
                   12387: sub symbclean {
                   12388:     my $symb=shift;
1.568     albertel 12389:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12390: # remove version from map
                   12391:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12392: 
1.210     www      12393: # remove version from URL
                   12394:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12395: 
1.507     www      12396: # remove wrapper
                   12397: 
1.510     www      12398:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12399:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12400:     return $symb;
1.409     www      12401: }
                   12402: 
                   12403: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12404: 
                   12405: sub encode_symb {
                   12406:     my ($map,$resid,$url)=@_;
                   12407:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12408: }
1.409     www      12409: 
                   12410: sub decode_symb {
1.568     albertel 12411:     my $symb=shift;
                   12412:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12413:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12414:     return (&fixversion($map),$resid,&fixversion($url));
                   12415: }
                   12416: 
                   12417: sub fixversion {
                   12418:     my $fn=shift;
1.609     banghart 12419:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12420:     my %bighash;
                   12421:     my $uri=&clutter($fn);
1.620     albertel 12422:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12423: # is this cached?
1.599     albertel 12424:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12425:     if (defined($cached)) { return $result; }
                   12426: # unfortunately not cached, or expired
1.620     albertel 12427:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12428: 	    &GDBM_READER(),0640)) {
                   12429:  	if ($bighash{'version_'.$uri}) {
                   12430:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12431:  	    unless (($version eq 'mostrecent') || 
                   12432: 		    ($version==&getversion($uri))) {
1.440     www      12433:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12434:  	    }
                   12435:  	}
                   12436:  	untie %bighash;
1.413     www      12437:     }
1.599     albertel 12438:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12439: }
                   12440: 
                   12441: sub deversion {
                   12442:     my $url=shift;
                   12443:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12444:     return $url;
1.210     www      12445: }
                   12446: 
1.31      www      12447: # ------------------------------------------------------ Return symb list entry
                   12448: 
                   12449: sub symbread {
1.1172.2.66  raeburn  12450:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12451:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12452:     if (defined($env{$cache_str})) {
                   12453:         if ($ignorecachednull) {
                   12454:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12455:         } else {
                   12456:             return $env{$cache_str};
                   12457:         }
                   12458:     }
1.242     www      12459: # no filename provided? try from environment
1.1172.2.54  raeburn  12460:     unless ($thisfn) {
1.620     albertel 12461:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12462:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12463:         }
                   12464:         $thisfn=$env{'request.filename'};
1.44      www      12465:     }
1.569     albertel 12466:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12467: # is that filename actually a symb? Verify, clean, and return
                   12468:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12469: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12470: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12471: 	}
1.242     www      12472:     }
1.44      www      12473:     $thisfn=declutter($thisfn);
1.31      www      12474:     my %hash;
1.37      www      12475:     my %bighash;
                   12476:     my $syval='';
1.620     albertel 12477:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12478:         my $targetfn = $thisfn;
1.609     banghart 12479:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12480:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12481:         }
1.687     albertel 12482: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12483: 	    $targetfn=$1;
                   12484: 	}
1.620     albertel 12485:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12486:                       &GDBM_READER(),0640)) {
1.481     raeburn  12487: 	    $syval=$hash{$targetfn};
1.37      www      12488:             untie(%hash);
                   12489:         }
                   12490: # ---------------------------------------------------------- There was an entry
                   12491:         if ($syval) {
1.601     albertel 12492: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12493: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12494: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12495: 		    #return $env{$cache_str}='';
1.601     albertel 12496: 		#}    
                   12497: 		#$syval.=$1;
                   12498: 	    #}
1.37      www      12499:         } else {
                   12500: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12501:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12502:                             &GDBM_READER(),0640)) {
1.37      www      12503: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12504:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12505:               unless ($ids) { 
                   12506:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12507:               }
                   12508:               unless ($ids) {
                   12509: # alias?
                   12510: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12511:               }
1.37      www      12512:               if ($ids) {
                   12513: # ------------------------------------------------------------------- Has ID(s)
                   12514:                  my @possibilities=split(/\,/,$ids);
1.39      www      12515:                  if ($#possibilities==0) {
                   12516: # ----------------------------------------------- There is only one possibility
1.37      www      12517: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12518: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12519: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12520:                      if (ref($possibles) eq 'HASH') {
                   12521:                          $possibles->{$syval} = 1;
                   12522:                      }
                   12523:                      if ($checkforblock) {
                   12524:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12525:                          if (@blockers) {
                   12526:                              $syval = '';
                   12527:                              return;
                   12528:                          }
                   12529:                      }
                   12530:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12531: # ------------------------------------------ There is more than one possibility
                   12532:                      my $realpossible=0;
1.800     albertel 12533:                      foreach my $id (@possibilities) {
                   12534: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12535:                          my $canaccess;
                   12536:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12537:                              $canaccess = 1;
                   12538:                          } else {
                   12539:                              $canaccess = &allowed('bre',$file);
                   12540:                          }
                   12541:                          if ($canaccess) {
                   12542:          		     my ($mapid,$resid)=split(/\./,$id);
                   12543:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12544:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12545:                                                              $resid,$thisfn);
                   12546:                                  if (ref($possibles) eq 'HASH') {
                   12547:                                      $possibles->{$syval} = 1;
                   12548:                                  }
                   12549:                                  if ($checkforblock) {
                   12550:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12551:                                      unless (@blockers > 0) {
                   12552:                                          $syval = $poss_syval;
                   12553:                                          $realpossible++;
                   12554:                                      }
                   12555:                                  } else {
                   12556:                                      $syval = $poss_syval;
                   12557:                                      $realpossible++;
                   12558:                                  }
                   12559:                              }
1.39      www      12560: 			 }
1.191     harris41 12561:                      }
1.39      www      12562: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12563:                  } else {
                   12564:                      $syval='';
1.37      www      12565:                  }
                   12566: 	      }
1.1172.2.66  raeburn  12567:               untie(%bighash);
1.481     raeburn  12568:            }
1.31      www      12569:         }
1.62      www      12570:         if ($syval) {
1.620     albertel 12571: 	    return $env{$cache_str}=$syval;
1.62      www      12572:         }
1.31      www      12573:     }
1.949     raeburn  12574:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12575:     return $env{$cache_str}='';
1.31      www      12576: }
                   12577: 
                   12578: # ---------------------------------------------------------- Return random seed
                   12579: 
1.32      www      12580: sub numval {
                   12581:     my $txt=shift;
                   12582:     $txt=~tr/A-J/0-9/;
                   12583:     $txt=~tr/a-j/0-9/;
                   12584:     $txt=~tr/K-T/0-9/;
                   12585:     $txt=~tr/k-t/0-9/;
                   12586:     $txt=~tr/U-Z/0-5/;
                   12587:     $txt=~tr/u-z/0-5/;
                   12588:     $txt=~s/\D//g;
1.564     albertel 12589:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12590:     return int($txt);
1.368     albertel 12591: }
                   12592: 
1.484     albertel 12593: sub numval2 {
                   12594:     my $txt=shift;
                   12595:     $txt=~tr/A-J/0-9/;
                   12596:     $txt=~tr/a-j/0-9/;
                   12597:     $txt=~tr/K-T/0-9/;
                   12598:     $txt=~tr/k-t/0-9/;
                   12599:     $txt=~tr/U-Z/0-5/;
                   12600:     $txt=~tr/u-z/0-5/;
                   12601:     $txt=~s/\D//g;
                   12602:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12603:     my $total;
                   12604:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12605:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12606:     return int($total);
                   12607: }
                   12608: 
1.575     albertel 12609: sub numval3 {
                   12610:     use integer;
                   12611:     my $txt=shift;
                   12612:     $txt=~tr/A-J/0-9/;
                   12613:     $txt=~tr/a-j/0-9/;
                   12614:     $txt=~tr/K-T/0-9/;
                   12615:     $txt=~tr/k-t/0-9/;
                   12616:     $txt=~tr/U-Z/0-5/;
                   12617:     $txt=~tr/u-z/0-5/;
                   12618:     $txt=~s/\D//g;
                   12619:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12620:     my $total;
                   12621:     foreach my $val (@txts) { $total+=$val; }
                   12622:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12623:     return $total;
                   12624: }
                   12625: 
1.675     albertel 12626: sub digest {
                   12627:     my ($data)=@_;
                   12628:     my $digest=&Digest::MD5::md5($data);
                   12629:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12630:     my ($e,$f);
                   12631:     {
                   12632:         use integer;
                   12633:         $e=($a+$b);
                   12634:         $f=($c+$d);
                   12635:         if ($_64bit) {
                   12636:             $e=(($e<<32)>>32);
                   12637:             $f=(($f<<32)>>32);
                   12638:         }
                   12639:     }
                   12640:     if (wantarray) {
                   12641: 	return ($e,$f);
                   12642:     } else {
                   12643: 	my $g;
                   12644: 	{
                   12645: 	    use integer;
                   12646: 	    $g=($e+$f);
                   12647: 	    if ($_64bit) {
                   12648: 		$g=(($g<<32)>>32);
                   12649: 	    }
                   12650: 	}
                   12651: 	return $g;
                   12652:     }
                   12653: }
                   12654: 
1.368     albertel 12655: sub latest_rnd_algorithm_id {
1.675     albertel 12656:     return '64bit5';
1.366     albertel 12657: }
1.32      www      12658: 
1.503     albertel 12659: sub get_rand_alg {
                   12660:     my ($courseid)=@_;
1.790     albertel 12661:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12662:     if ($courseid) {
1.620     albertel 12663: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12664:     }
                   12665:     return &latest_rnd_algorithm_id();
                   12666: }
                   12667: 
1.562     albertel 12668: sub validCODE {
                   12669:     my ($CODE)=@_;
                   12670:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12671:     return 0;
                   12672: }
                   12673: 
1.491     albertel 12674: sub getCODE {
1.620     albertel 12675:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12676:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12677: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12678: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12679: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12680:     }
                   12681:     return undef;
                   12682: }
1.1133    foxr     12683: #
                   12684: #  Determines the random seed for a specific context:
                   12685: #
                   12686: # parameters:
                   12687: #   symb      - in course context the symb for the seed.
                   12688: #   course_id - The course id of the form domain_coursenum.
                   12689: #   domain    - Domain for the user.
                   12690: #   course    - Course for the user.
                   12691: #   cenv      - environment of the course.
                   12692: #
                   12693: # NOTE:
                   12694: #   All parameters are picked out of the environment if missing
                   12695: #   or not defined.
                   12696: #   If a symb cannot be determined the current time is used instead.
                   12697: #
                   12698: #  For a given well defined symb, courside, domain, username,
                   12699: #  and course environment, the seed is reproducible.
                   12700: #
1.31      www      12701: sub rndseed {
1.1133    foxr     12702:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12703:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12704:     if (!defined($symb)) {
1.366     albertel 12705: 	unless ($symb=$wsymb) { return time; }
                   12706:     }
1.1146    foxr     12707:     if (!defined $courseid) { 
                   12708: 	$courseid=$wcourseid; 
                   12709:     }
                   12710:     if (!defined $domain) { $domain=$wdomain; }
                   12711:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12712: 
                   12713:     my $which;
                   12714:     if (defined($cenv->{'rndseed'})) {
                   12715: 	$which = $cenv->{'rndseed'};
                   12716:     } else {
                   12717: 	$which =&get_rand_alg($courseid);
                   12718:     }
1.491     albertel 12719:     if (defined(&getCODE())) {
1.675     albertel 12720: 	if ($which eq '64bit5') {
                   12721: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12722: 	} elsif ($which eq '64bit4') {
1.575     albertel 12723: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12724: 	} else {
                   12725: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12726: 	}
1.675     albertel 12727:     } elsif ($which eq '64bit5') {
                   12728: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12729:     } elsif ($which eq '64bit4') {
                   12730: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12731:     } elsif ($which eq '64bit3') {
                   12732: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12733:     } elsif ($which eq '64bit2') {
                   12734: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12735:     } elsif ($which eq '64bit') {
                   12736: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12737:     }
                   12738:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12739: }
                   12740: 
                   12741: sub rndseed_32bit {
                   12742:     my ($symb,$courseid,$domain,$username)=@_;
                   12743:     {
                   12744: 	use integer;
                   12745: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12746: 	my $symbseed=numval($symb) << 22;
                   12747: 	my $namechck=unpack("%32C*",$username) << 17;
                   12748: 	my $nameseed=numval($username) << 12;
                   12749: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12750: 	my $courseseed=unpack("%32C*",$courseid);
                   12751: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12752: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12753: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12754: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12755: 	return $num;
                   12756:     }
                   12757: }
                   12758: 
                   12759: sub rndseed_64bit {
                   12760:     my ($symb,$courseid,$domain,$username)=@_;
                   12761:     {
                   12762: 	use integer;
                   12763: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12764: 	my $symbseed=numval($symb) << 10;
                   12765: 	my $namechck=unpack("%32S*",$username);
                   12766: 	
                   12767: 	my $nameseed=numval($username) << 21;
                   12768: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12769: 	my $courseseed=unpack("%32S*",$courseid);
                   12770: 	
                   12771: 	my $num1=$symbchck+$symbseed+$namechck;
                   12772: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12773: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12774: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12775: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12776: 	return "$num1,$num2";
1.155     albertel 12777:     }
1.366     albertel 12778: }
                   12779: 
1.443     albertel 12780: sub rndseed_64bit2 {
                   12781:     my ($symb,$courseid,$domain,$username)=@_;
                   12782:     {
                   12783: 	use integer;
                   12784: 	# strings need to be an even # of cahracters long, it it is odd the
                   12785:         # last characters gets thrown away
                   12786: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12787: 	my $symbseed=numval($symb) << 10;
                   12788: 	my $namechck=unpack("%32S*",$username.' ');
                   12789: 	
                   12790: 	my $nameseed=numval($username) << 21;
1.501     albertel 12791: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12792: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12793: 	
                   12794: 	my $num1=$symbchck+$symbseed+$namechck;
                   12795: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12796: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12797: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12798: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12799: 	return "$num1,$num2";
                   12800:     }
                   12801: }
                   12802: 
                   12803: sub rndseed_64bit3 {
                   12804:     my ($symb,$courseid,$domain,$username)=@_;
                   12805:     {
                   12806: 	use integer;
                   12807: 	# strings need to be an even # of cahracters long, it it is odd the
                   12808:         # last characters gets thrown away
                   12809: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12810: 	my $symbseed=numval2($symb) << 10;
                   12811: 	my $namechck=unpack("%32S*",$username.' ');
                   12812: 	
                   12813: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12814: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12815: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12816: 	
                   12817: 	my $num1=$symbchck+$symbseed+$namechck;
                   12818: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12819: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12820: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12821: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12822: 	
1.503     albertel 12823: 	return "$num1:$num2";
1.443     albertel 12824:     }
                   12825: }
                   12826: 
1.575     albertel 12827: sub rndseed_64bit4 {
                   12828:     my ($symb,$courseid,$domain,$username)=@_;
                   12829:     {
                   12830: 	use integer;
                   12831: 	# strings need to be an even # of cahracters long, it it is odd the
                   12832:         # last characters gets thrown away
                   12833: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12834: 	my $symbseed=numval3($symb) << 10;
                   12835: 	my $namechck=unpack("%32S*",$username.' ');
                   12836: 	
                   12837: 	my $nameseed=numval3($username) << 21;
                   12838: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12839: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12840: 	
                   12841: 	my $num1=$symbchck+$symbseed+$namechck;
                   12842: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12843: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12844: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12845: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12846: 	
1.575     albertel 12847: 	return "$num1:$num2";
                   12848:     }
                   12849: }
                   12850: 
1.675     albertel 12851: sub rndseed_64bit5 {
                   12852:     my ($symb,$courseid,$domain,$username)=@_;
                   12853:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12854:     return "$num1:$num2";
                   12855: }
                   12856: 
1.366     albertel 12857: sub rndseed_CODE_64bit {
                   12858:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12859:     {
1.366     albertel 12860: 	use integer;
1.443     albertel 12861: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12862: 	my $symbseed=numval2($symb);
1.491     albertel 12863: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12864: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12865: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12866: 	my $num1=$symbseed+$CODEchck;
                   12867: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12868: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12869: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12870: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12871: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12872: 	return "$num1:$num2";
1.366     albertel 12873:     }
                   12874: }
                   12875: 
1.575     albertel 12876: sub rndseed_CODE_64bit4 {
                   12877:     my ($symb,$courseid,$domain,$username)=@_;
                   12878:     {
                   12879: 	use integer;
                   12880: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12881: 	my $symbseed=numval3($symb);
                   12882: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12883: 	my $CODEseed=numval3(&getCODE());
                   12884: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12885: 	my $num1=$symbseed+$CODEchck;
                   12886: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12887: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12888: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12889: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12890: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12891: 	return "$num1:$num2";
                   12892:     }
                   12893: }
                   12894: 
1.675     albertel 12895: sub rndseed_CODE_64bit5 {
                   12896:     my ($symb,$courseid,$domain,$username)=@_;
                   12897:     my $code = &getCODE();
                   12898:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12899:     return "$num1:$num2";
                   12900: }
                   12901: 
1.366     albertel 12902: sub setup_random_from_rndseed {
                   12903:     my ($rndseed)=@_;
1.503     albertel 12904:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12905: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12906:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12907:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12908:         } else {
                   12909:             &Math::Random::random_set_seed($num1,$num2);
                   12910:         }
1.366     albertel 12911:     } else {
                   12912: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12913:     }
1.36      albertel 12914: }
                   12915: 
1.474     albertel 12916: sub latest_receipt_algorithm_id {
1.835     albertel 12917:     return 'receipt3';
1.474     albertel 12918: }
                   12919: 
1.480     www      12920: sub recunique {
                   12921:     my $fucourseid=shift;
                   12922:     my $unique;
1.835     albertel 12923:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12924: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12925: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12926:     } else {
                   12927: 	$unique=$perlvar{'lonReceipt'};
                   12928:     }
                   12929:     return unpack("%32C*",$unique);
                   12930: }
                   12931: 
                   12932: sub recprefix {
                   12933:     my $fucourseid=shift;
                   12934:     my $prefix;
1.835     albertel 12935:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12936: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12937: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12938:     } else {
                   12939: 	$prefix=$perlvar{'lonHostID'};
                   12940:     }
                   12941:     return unpack("%32C*",$prefix);
                   12942: }
                   12943: 
1.76      www      12944: sub ireceipt {
1.474     albertel 12945:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12946: 
                   12947:     my $return =&recprefix($fucourseid).'-';
                   12948: 
                   12949:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12950: 	$env{'request.state'} eq 'construct') {
                   12951: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12952: 	return $return;
                   12953:     }
                   12954: 
1.76      www      12955:     my $cuname=unpack("%32C*",$funame);
                   12956:     my $cudom=unpack("%32C*",$fudom);
                   12957:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12958:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12959:     my $cunique=&recunique($fucourseid);
1.474     albertel 12960:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12961:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12962: 
1.790     albertel 12963: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12964: 			       
                   12965: 	$return.= ($cunique%$cuname+
                   12966: 		   $cunique%$cudom+
                   12967: 		   $cusymb%$cuname+
                   12968: 		   $cusymb%$cudom+
                   12969: 		   $cucourseid%$cuname+
                   12970: 		   $cucourseid%$cudom+
                   12971: 		   $cpart%$cuname+
                   12972: 		   $cpart%$cudom);
                   12973:     } else {
                   12974: 	$return.= ($cunique%$cuname+
                   12975: 		   $cunique%$cudom+
                   12976: 		   $cusymb%$cuname+
                   12977: 		   $cusymb%$cudom+
                   12978: 		   $cucourseid%$cuname+
                   12979: 		   $cucourseid%$cudom);
                   12980:     }
                   12981:     return $return;
1.76      www      12982: }
                   12983: 
                   12984: sub receipt {
1.474     albertel 12985:     my ($part)=@_;
1.790     albertel 12986:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12987:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12988: }
1.260     ng       12989: 
1.790     albertel 12990: sub whichuser {
                   12991:     my ($passedsymb)=@_;
                   12992:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12993:     if (defined($env{'form.grade_symb'})) {
                   12994: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12995: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12996: 	if (!$allowed &&
                   12997: 	    exists($env{'request.course.sec'}) &&
                   12998: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12999: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13000: 			      '/'.$env{'request.course.sec'});
                   13001: 	}
                   13002: 	if ($allowed) {
                   13003: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13004: 	    $courseid=$tmp_courseid;
                   13005: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13006: 	    ($name)=&get_env_multiple('form.grade_username');
                   13007: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13008: 	}
                   13009:     }
                   13010:     if (!$passedsymb) {
                   13011: 	$symb=&symbread();
                   13012:     } else {
                   13013: 	$symb=$passedsymb;
                   13014:     }
                   13015:     $courseid=$env{'request.course.id'};
                   13016:     $domain=$env{'user.domain'};
                   13017:     $name=$env{'user.name'};
                   13018:     if ($name eq 'public' && $domain eq 'public') {
                   13019: 	if (!defined($env{'form.username'})) {
                   13020: 	    $env{'form.username'}.=time.rand(10000000);
                   13021: 	}
                   13022: 	$name.=$env{'form.username'};
                   13023:     }
                   13024:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13025: 
                   13026: }
                   13027: 
1.36      albertel 13028: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13029: # returns either the contents of the file or 
                   13030: # -1 if the file doesn't exist
1.481     raeburn  13031: #
                   13032: # if the target is a file that was uploaded via DOCS, 
                   13033: # a check will be made to see if a current copy exists on the local server,
                   13034: # if it does this will be served, otherwise a copy will be retrieved from
                   13035: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13036: # the local server.   
1.472     albertel 13037: 
1.36      albertel 13038: sub getfile {
1.538     albertel 13039:     my ($file) = @_;
1.609     banghart 13040:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13041:     &repcopy($file);
                   13042:     return &readfile($file);
                   13043: }
                   13044: 
                   13045: sub repcopy_userfile {
                   13046:     my ($file)=@_;
1.1142    raeburn  13047:     my $londocroot = $perlvar{'lonDocRoot'};
                   13048:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13049:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13050:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13051: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13052:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13053:     if (-e "$file") {
1.828     www      13054: # we already have a local copy, check it out
1.538     albertel 13055: 	my @fileinfo = stat($file);
1.828     www      13056: 	my $rtncode;
                   13057: 	my $info;
1.538     albertel 13058: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13059: 	if ($lwpresp ne 'ok') {
1.828     www      13060: # there is no such file anymore, even though we had a local copy
1.482     albertel 13061: 	    if ($rtncode eq '404') {
1.538     albertel 13062: 		unlink($file);
1.482     albertel 13063: 	    }
                   13064: 	    return -1;
                   13065: 	}
                   13066: 	if ($info < $fileinfo[9]) {
1.828     www      13067: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13068: 	    return 'ok';
1.828     www      13069: 	} else {
                   13070: # the file is outdated, get rid of it
                   13071: 	    unlink($file);
1.482     albertel 13072: 	}
1.828     www      13073:     }
                   13074: # one way or the other, at this point, we don't have the file
                   13075: # construct the correct path for the file
                   13076:     my @parts = ($cdom,$cnum); 
                   13077:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13078: 	push @parts, split(/\//,$1);
                   13079:     }
                   13080:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13081:     foreach my $part (@parts) {
                   13082: 	$path .= '/'.$part;
                   13083: 	if (!-e $path) {
                   13084: 	    mkdir($path,0770);
1.482     albertel 13085: 	}
                   13086:     }
1.828     www      13087: # now the path exists for sure
                   13088: # get a user agent
                   13089:     my $ua=new LWP::UserAgent;
                   13090:     my $transferfile=$file.'.in.transfer';
                   13091: # FIXME: this should flock
                   13092:     if (-e $transferfile) { return 'ok'; }
                   13093:     my $request;
                   13094:     $uri=~s/^\///;
1.980     raeburn  13095:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13096:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13097:     my $protocol = $protocol{$homeserver};
                   13098:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13099:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13100:     my $response=$ua->request($request,$transferfile);
                   13101: # did it work?
                   13102:     if ($response->is_error()) {
                   13103: 	unlink($transferfile);
                   13104: 	&logthis("Userfile repcopy failed for $uri");
                   13105: 	return -1;
                   13106:     }
                   13107: # worked, rename the transfer file
                   13108:     rename($transferfile,$file);
1.607     raeburn  13109:     return 'ok';
1.481     raeburn  13110: }
                   13111: 
1.517     albertel 13112: sub tokenwrapper {
                   13113:     my $uri=shift;
1.980     raeburn  13114:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13115:     $uri=~s|^/||;
1.620     albertel 13116:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13117:     my $token=$1;
1.552     albertel 13118:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13119:     if ($udom && $uname && $file) {
                   13120: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13121:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13122:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13123:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13124:         my $protocol = $protocol{$homeserver};
                   13125:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13126:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13127:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13128:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13129:     } else {
                   13130:         return '/adm/notfound.html';
                   13131:     }
                   13132: }
                   13133: 
1.828     www      13134: # call with reqtype HEAD: get last modification time
                   13135: # call with reqtype GET: get the file contents
                   13136: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13137: #
1.481     raeburn  13138: sub getuploaded {
                   13139:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13140:     $uri=~s/^\///;
1.980     raeburn  13141:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13142:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13143:     my $protocol = $protocol{$homeserver};
                   13144:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13145:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13146:     my $ua=new LWP::UserAgent;
                   13147:     my $request=new HTTP::Request($reqtype,$uri);
                   13148:     my $response=$ua->request($request);
                   13149:     $$rtncode = $response->code;
1.482     albertel 13150:     if (! $response->is_success()) {
                   13151: 	return 'failed';
                   13152:     }      
                   13153:     if ($reqtype eq 'HEAD') {
1.486     www      13154: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13155:     } elsif ($reqtype eq 'GET') {
                   13156: 	$$info = $response->content;
1.472     albertel 13157:     }
1.482     albertel 13158:     return 'ok';
1.36      albertel 13159: }
                   13160: 
1.481     raeburn  13161: sub readfile {
                   13162:     my $file = shift;
                   13163:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13164:     my $fh;
1.1172.2.96  raeburn  13165:     open($fh,"<",$file);
1.481     raeburn  13166:     my $a='';
1.800     albertel 13167:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13168:     return $a;
                   13169: }
                   13170: 
1.36      albertel 13171: sub filelocation {
1.590     banghart 13172:     my ($dir,$file) = @_;
                   13173:     my $location;
                   13174:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13175: 
                   13176:     if ($file =~ m-^/adm/-) {
                   13177: 	$file=~s-^/adm/wrapper/-/-;
                   13178: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13179:     }
1.882     albertel 13180: 
1.1139    www      13181:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13182:         $location = $file;
1.609     banghart 13183:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13184:         my ($udom,$uname,$filename)=
1.811     albertel 13185:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13186:         my $home=&homeserver($uname,$udom);
                   13187:         my $is_me=0;
                   13188:         my @ids=&current_machine_ids();
                   13189:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13190:         if ($is_me) {
1.1117    foxr     13191:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13192:         } else {
                   13193:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13194:   	      $udom.'/'.$uname.'/'.$filename;
                   13195:         }
1.882     albertel 13196:     } elsif ($file =~ m-^/adm/-) {
                   13197: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13198:     } else {
                   13199:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13200:         $file=~s:^/(res|priv)/:/:;
                   13201:         my $space=$1;
1.590     banghart 13202:         if ( !( $file =~ m:^/:) ) {
                   13203:             $location = $dir. '/'.$file;
                   13204:         } else {
1.1142    raeburn  13205:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13206:         }
1.59      albertel 13207:     }
1.590     banghart 13208:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13209:     while ($location=~m{/\.\./}) {
                   13210: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13211: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13212: 	} else {
                   13213: 	    $location=~ s{/\.\./}{/}g;
                   13214: 	}
                   13215:     } #remove dir/..
1.590     banghart 13216:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13217:     return $location;
1.46      www      13218: }
1.36      albertel 13219: 
1.46      www      13220: sub hreflocation {
                   13221:     my ($dir,$file)=@_;
1.980     raeburn  13222:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13223: 	$file=filelocation($dir,$file);
1.700     albertel 13224:     } elsif ($file=~m-^/adm/-) {
                   13225: 	$file=~s-^/adm/wrapper/-/-;
                   13226: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13227:     }
                   13228:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13229: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13230:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13231: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13232: 	        {/uploaded/$1/$2/}x;
1.46      www      13233:     }
1.913     albertel 13234:     if ($file=~ m{^/userfiles/}) {
                   13235: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13236:     }
1.462     albertel 13237:     return $file;
1.465     albertel 13238: }
                   13239: 
1.1139    www      13240: 
                   13241: 
                   13242: 
                   13243: 
1.465     albertel 13244: sub current_machine_domains {
1.853     albertel 13245:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13246: }
                   13247: 
                   13248: sub machine_domains {
                   13249:     my ($hostname) = @_;
1.465     albertel 13250:     my @domains;
1.838     albertel 13251:     my %hostname = &all_hostnames();
1.465     albertel 13252:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13253: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13254: 	if ($hostname eq $name) {
1.844     albertel 13255: 	    push(@domains,&host_domain($id));
1.465     albertel 13256: 	}
                   13257:     }
                   13258:     return @domains;
                   13259: }
                   13260: 
                   13261: sub current_machine_ids {
1.853     albertel 13262:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13263: }
                   13264: 
                   13265: sub machine_ids {
                   13266:     my ($hostname) = @_;
                   13267:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13268:     my @ids;
1.888     albertel 13269:     my %name_to_host = &all_names();
1.889     albertel 13270:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13271: 	return @{ $name_to_host{$hostname} };
                   13272:     }
                   13273:     return;
1.31      www      13274: }
                   13275: 
1.824     raeburn  13276: sub additional_machine_domains {
                   13277:     my @domains;
1.1172.2.96  raeburn  13278:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13279:     while( my $line = <$fh>) {
                   13280:         $line =~ s/\s//g;
                   13281:         push(@domains,$line);
                   13282:     }
                   13283:     return @domains;
                   13284: }
                   13285: 
                   13286: sub default_login_domain {
                   13287:     my $domain = $perlvar{'lonDefDomain'};
                   13288:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13289:     foreach my $posdom (&current_machine_domains(),
                   13290:                         &additional_machine_domains()) {
                   13291:         if (lc($posdom) eq lc($testdomain)) {
                   13292:             $domain=$posdom;
                   13293:             last;
                   13294:         }
                   13295:     }
                   13296:     return $domain;
                   13297: }
                   13298: 
1.1172.2.106  raeburn  13299: sub shared_institution {
                   13300:     my ($dom) = @_;
                   13301:     my $same_intdom;
                   13302:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13303:     if ($hostintdom ne '') {
                   13304:         my %iphost = &get_iphost();
                   13305:         my $primary_id = &domain($dom,'primary');
                   13306:         my $primary_ip = &get_host_ip($primary_id);
                   13307:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13308:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13309:                 my $intdom = &internet_dom($id);
                   13310:                 if ($intdom eq $hostintdom) {
                   13311:                     $same_intdom = 1;
                   13312:                     last;
                   13313:                 }
                   13314:             }
                   13315:         }
                   13316:     }
                   13317:     return $same_intdom;
                   13318: }
                   13319: 
1.1172.2.118.  .3(raebu 13320:20): sub uses_sts {
                   13321:20):     my ($ignore_cache) = @_;
                   13322:20):     my $lonhost = $perlvar{'lonHostID'};
                   13323:20):     my $hostname = &hostname($lonhost);
                   13324:20):     my $sts_on;
                   13325:20):     if ($protocol{$lonhost} eq 'https') {
                   13326:20):         my $cachetime = 12*3600;
                   13327:20):         if (!$ignore_cache) {
                   13328:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13329:20):             if (defined($cached)) {
                   13330:20):                 return $sts_on;
                   13331:20):             }
                   13332:20):         }
          .4(raebu 13333:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13334:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13335:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13336:20):         my $response=$ua->request($request);
          .3(raebu 13337:20):         if ($response->is_success) {
                   13338:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13339:20):             if ($has_sts eq '') {
                   13340:20):                 $sts_on = 0;
                   13341:20):             } else {
                   13342:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13343:20):                     my $maxage = $1;
                   13344:20):                     if ($maxage) {
                   13345:20):                         $sts_on = 1;
                   13346:20):                     } else {
                   13347:20):                         $sts_on = 0;
                   13348:20):                     }
                   13349:20):                 } else {
                   13350:20):                     $sts_on = 0;
                   13351:20):                 }
                   13352:20):             }
                   13353:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13354:20):         }
                   13355:20):     }
                   13356:20):     return;
                   13357:20): }
                   13358:20): 
1.31      www      13359: # ------------------------------------------------------------- Declutters URLs
                   13360: 
                   13361: sub declutter {
                   13362:     my $thisfn=shift;
1.569     albertel 13363:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13364:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13365:         $thisfn=~s{^/home/httpd/html}{};
                   13366:     }
1.31      www      13367:     $thisfn=~s/^\///;
1.697     albertel 13368:     $thisfn=~s|^adm/wrapper/||;
                   13369:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13370:     $thisfn=~s/^res\///;
1.1172    bisitz   13371:     $thisfn=~s/^priv\///;
1.1032    raeburn  13372:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13373:         $thisfn=~s/\?.+$//;
                   13374:     }
1.268     www      13375:     return $thisfn;
                   13376: }
                   13377: 
                   13378: # ------------------------------------------------------------- Clutter up URLs
                   13379: 
                   13380: sub clutter {
                   13381:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13382:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13383: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13384:        $thisfn='/res'.$thisfn; 
                   13385:     }
1.1031    raeburn  13386:     if ($thisfn !~m|^/adm|) {
                   13387: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13388: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13389: 	} else {
                   13390: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13391: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13392: 	    if ($embstyle eq 'ssi'
                   13393: 		|| ($embstyle eq 'hdn')
                   13394: 		|| ($embstyle eq 'rat')
                   13395: 		|| ($embstyle eq 'prv')
                   13396: 		|| ($embstyle eq 'ign')) {
                   13397: 		#do nothing with these
                   13398: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13399: 		|| ($embstyle eq 'emb')
                   13400: 		|| ($embstyle eq 'wrp')) {
                   13401: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13402: 	    } elsif ($embstyle eq 'unk'
                   13403: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13404: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13405: 	    } else {
1.718     www      13406: #		&logthis("Got a blank emb style");
1.695     albertel 13407: 	    }
1.694     albertel 13408: 	}
1.1172.2.118.  .1(raebu 13409:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13410:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13411:     }
1.31      www      13412:     return $thisfn;
1.12      www      13413: }
                   13414: 
1.787     albertel 13415: sub clutter_with_no_wrapper {
                   13416:     my $uri = &clutter(shift);
                   13417:     if ($uri =~ m-^/adm/-) {
                   13418: 	$uri =~ s-^/adm/wrapper/-/-;
                   13419: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13420:     }
                   13421:     return $uri;
                   13422: }
                   13423: 
1.557     albertel 13424: sub freeze_escape {
                   13425:     my ($value)=@_;
                   13426:     if (ref($value)) {
                   13427: 	$value=&nfreeze($value);
                   13428: 	return '__FROZEN__'.&escape($value);
                   13429:     }
                   13430:     return &escape($value);
                   13431: }
                   13432: 
1.11      www      13433: 
1.557     albertel 13434: sub thaw_unescape {
                   13435:     my ($value)=@_;
                   13436:     if ($value =~ /^__FROZEN__/) {
                   13437: 	substr($value,0,10,undef);
                   13438: 	$value=&unescape($value);
                   13439: 	return &thaw($value);
                   13440:     }
                   13441:     return &unescape($value);
                   13442: }
                   13443: 
1.436     albertel 13444: sub correct_line_ends {
                   13445:     my ($result)=@_;
                   13446:     $$result =~s/\r\n/\n/mg;
                   13447:     $$result =~s/\r/\n/mg;
1.415     albertel 13448: }
1.1       albertel 13449: # ================================================================ Main Program
                   13450: 
1.184     www      13451: sub goodbye {
1.204     albertel 13452:    &logthis("Starting Shut down");
1.443     albertel 13453: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13454:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13455: #converted
1.599     albertel 13456: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13457:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13458: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13459: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13460: #1.1 only
1.870     albertel 13461: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13462: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13463: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13464: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13465:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13466:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13467:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13468:    &flushcourselogs();
                   13469:    &logthis("Shutting down");
                   13470: }
                   13471: 
1.852     albertel 13472: sub get_dns {
1.1172.2.17  raeburn  13473:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13474:     if (!$ignore_cache) {
                   13475: 	my ($content,$cached)=
                   13476: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13477: 	if ($cached) {
1.1172.2.17  raeburn  13478: 	    &$func($content,$hashref);
1.869     albertel 13479: 	    return;
                   13480: 	}
                   13481:     }
                   13482: 
                   13483:     my %alldns;
1.1172.2.96  raeburn  13484:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13485:         foreach my $dns (<$config>) {
                   13486: 	    next if ($dns !~ /^\^(\S*)/x);
                   13487:             my $line = $1;
                   13488:             my ($host,$protocol) = split(/:/,$line);
                   13489:             if ($protocol ne 'https') {
                   13490:                 $protocol = 'http';
                   13491:             }
                   13492: 	    $alldns{$host} = $protocol;
1.979     raeburn  13493:         }
1.1172.2.96  raeburn  13494:         close($config);
1.869     albertel 13495:     }
                   13496:     while (%alldns) {
1.1172.2.52  raeburn  13497: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13498: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13499:         $ua->timeout(30);
1.979     raeburn  13500: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13501: 	my $response=$ua->request($request);
1.979     raeburn  13502:         delete($alldns{$dns});
1.852     albertel 13503: 	next if ($response->is_error());
                   13504: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13505:         unless ($nocache) {
1.1172.2.23  raeburn  13506: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13507:         }
                   13508: 	&$func(\@content,$hashref);
1.869     albertel 13509: 	return;
1.852     albertel 13510:     }
1.871     albertel 13511:     my $which = (split('/',$url))[3];
                   13512:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13513:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13514:         my @content = <$config>;
                   13515:         &$func(\@content,$hashref);
                   13516:     }
1.1172.2.17  raeburn  13517:     return;
                   13518: }
                   13519: 
                   13520: # ------------------------------------------------------Get DNS checksums file
                   13521: sub parse_dns_checksums_tab {
                   13522:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13523:     my $lonhost = $perlvar{'lonHostID'};
                   13524:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13525:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13526:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13527:     my $webconfdir = '/etc/httpd/conf';
                   13528:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13529:         $webconfdir = '/etc/apache2';
                   13530:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13531:         if ($1 >= 10) {
                   13532:             $webconfdir = '/etc/apache2';
                   13533:         }
                   13534:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13535:         if ($1 >= 10.0) {
                   13536:             $webconfdir = '/etc/apache2';
                   13537:         }
                   13538:     }
1.1172.2.17  raeburn  13539:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13540:     my (%chksum,%revnum);
                   13541:     if (ref($lines) eq 'ARRAY') {
                   13542:         chomp(@{$lines});
1.1172.2.34  raeburn  13543:         my $version = shift(@{$lines});
                   13544:         if ($version eq $release) {
1.1172.2.17  raeburn  13545:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13546:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13547:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13548:                     if ($webconfdir eq '/etc/apache2') {
                   13549:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13550:                     }
                   13551:                 }
1.1172.2.34  raeburn  13552:                 $chksum{$file} = $shasum;
                   13553:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13554:             }
                   13555:             if (ref($hashref) eq 'HASH') {
                   13556:                 %{$hashref} = (
                   13557:                                 sums     => \%chksum,
                   13558:                                 versions => \%revnum,
                   13559:                               );
                   13560:             }
                   13561:         }
                   13562:     }
1.869     albertel 13563:     return;
1.852     albertel 13564: }
1.1172.2.17  raeburn  13565: 
                   13566: sub fetch_dns_checksums {
                   13567:     my %checksums;
1.1172.2.34  raeburn  13568:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13569:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13570:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13571:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13572:              \%checksums);
                   13573:     return \%checksums;
                   13574: }
                   13575: 
1.327     albertel 13576: # ------------------------------------------------------------ Read domain file
                   13577: {
1.852     albertel 13578:     my $loaded;
1.846     albertel 13579:     my %domain;
                   13580: 
1.852     albertel 13581:     sub parse_domain_tab {
                   13582: 	my ($lines) = @_;
                   13583: 	foreach my $line (@$lines) {
                   13584: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13585: 
1.846     albertel 13586: 	    chomp($line);
1.852     albertel 13587: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13588: 	    my %this_domain;
                   13589: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13590: 			       'lang_def', 'city', 'longi', 'lati',
                   13591: 			       'primary') {
                   13592: 		$this_domain{$field} = shift(@elements);
                   13593: 	    }
                   13594: 	    $domain{$name} = \%this_domain;
1.852     albertel 13595: 	}
                   13596:     }
1.864     albertel 13597: 
                   13598:     sub reset_domain_info {
                   13599: 	undef($loaded);
                   13600: 	undef(%domain);
                   13601:     }
                   13602: 
1.852     albertel 13603:     sub load_domain_tab {
1.1172.2.70  raeburn  13604: 	my ($ignore_cache,$nocache) = @_;
                   13605: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13606: 	my $fh;
1.1172.2.96  raeburn  13607: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13608: 	    my @lines = <$fh>;
                   13609: 	    &parse_domain_tab(\@lines);
1.448     albertel 13610: 	}
1.852     albertel 13611: 	close($fh);
                   13612: 	$loaded = 1;
1.327     albertel 13613:     }
1.846     albertel 13614: 
                   13615:     sub domain {
1.852     albertel 13616: 	&load_domain_tab() if (!$loaded);
                   13617: 
1.846     albertel 13618: 	my ($name,$what) = @_;
                   13619: 	return if ( !exists($domain{$name}) );
                   13620: 
                   13621: 	if (!$what) {
                   13622: 	    return $domain{$name}{'description'};
                   13623: 	}
                   13624: 	return $domain{$name}{$what};
                   13625:     }
1.974     raeburn  13626: 
                   13627:     sub domain_info {
                   13628:         &load_domain_tab() if (!$loaded);
                   13629:         return %domain;
                   13630:     }
                   13631: 
1.327     albertel 13632: }
                   13633: 
                   13634: 
1.1       albertel 13635: # ------------------------------------------------------------- Read hosts file
                   13636: {
1.838     albertel 13637:     my %hostname;
1.844     albertel 13638:     my %hostdom;
1.845     albertel 13639:     my %libserv;
1.852     albertel 13640:     my $loaded;
1.888     albertel 13641:     my %name_to_host;
1.1074    raeburn  13642:     my %internetdom;
1.1107    raeburn  13643:     my %LC_dns_serv;
1.852     albertel 13644: 
                   13645:     sub parse_hosts_tab {
                   13646: 	my ($file) = @_;
                   13647: 	foreach my $configline (@$file) {
                   13648: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13649:             chomp($configline);
                   13650: 	    if ($configline =~ /^\^/) {
                   13651:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13652:                     $LC_dns_serv{$1} = 1;
                   13653:                 }
                   13654:                 next;
                   13655:             }
1.1074    raeburn  13656: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13657: 	    $name=~s/\s//g;
                   13658: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13659:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13660:                     my $curr = $hostname{$id};
                   13661:                     my $skip;
                   13662:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13663:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13664:                             $skip = 1;
                   13665:                         } else {
                   13666:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13667:                         }
                   13668:                     }
                   13669:                     unless ($skip) {
                   13670:                         push(@{$name_to_host{$name}},$id);
                   13671:                     }
                   13672:                 } else {
                   13673:                     push(@{$name_to_host{$name}},$id);
                   13674:                 }
1.852     albertel 13675: 		$hostname{$id}=$name;
                   13676: 		$hostdom{$id}=$domain;
                   13677: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13678:                 if (defined($protocol)) {
                   13679:                     if ($protocol eq 'https') {
                   13680:                         $protocol{$id} = $protocol;
                   13681:                     } else {
                   13682:                         $protocol{$id} = 'http'; 
                   13683:                     }
1.968     raeburn  13684:                 } else {
1.969     raeburn  13685:                     $protocol{$id} = 'http';
1.968     raeburn  13686:                 }
1.1074    raeburn  13687:                 if (defined($intdom)) {
                   13688:                     $internetdom{$id} = $intdom;
                   13689:                 }
1.852     albertel 13690: 	    }
                   13691: 	}
                   13692:     }
1.864     albertel 13693:     
                   13694:     sub reset_hosts_info {
1.897     albertel 13695: 	&purge_remembered();
1.864     albertel 13696: 	&reset_domain_info();
                   13697: 	&reset_hosts_ip_info();
1.892     albertel 13698: 	undef(%name_to_host);
1.864     albertel 13699: 	undef(%hostname);
                   13700: 	undef(%hostdom);
                   13701: 	undef(%libserv);
                   13702: 	undef($loaded);
                   13703:     }
1.1       albertel 13704: 
1.852     albertel 13705:     sub load_hosts_tab {
1.1172.2.70  raeburn  13706: 	my ($ignore_cache,$nocache) = @_;
                   13707: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13708: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13709: 	my @config = <$config>;
                   13710: 	&parse_hosts_tab(\@config);
                   13711: 	close($config);
                   13712: 	$loaded=1;
1.1       albertel 13713:     }
1.852     albertel 13714: 
1.838     albertel 13715:     sub hostname {
1.852     albertel 13716: 	&load_hosts_tab() if (!$loaded);
                   13717: 
1.838     albertel 13718: 	my ($lonid) = @_;
                   13719: 	return $hostname{$lonid};
                   13720:     }
1.845     albertel 13721: 
1.838     albertel 13722:     sub all_hostnames {
1.852     albertel 13723: 	&load_hosts_tab() if (!$loaded);
                   13724: 
1.838     albertel 13725: 	return %hostname;
                   13726:     }
1.845     albertel 13727: 
1.888     albertel 13728:     sub all_names {
1.1172.2.70  raeburn  13729:         my ($ignore_cache,$nocache) = @_;
                   13730: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13731: 
                   13732: 	return %name_to_host;
                   13733:     }
                   13734: 
1.974     raeburn  13735:     sub all_host_domain {
                   13736:         &load_hosts_tab() if (!$loaded);
                   13737:         return %hostdom;
                   13738:     }
                   13739: 
1.845     albertel 13740:     sub is_library {
1.852     albertel 13741: 	&load_hosts_tab() if (!$loaded);
                   13742: 
1.845     albertel 13743: 	return exists($libserv{$_[0]});
                   13744:     }
                   13745: 
                   13746:     sub all_library {
1.852     albertel 13747: 	&load_hosts_tab() if (!$loaded);
                   13748: 
1.845     albertel 13749: 	return %libserv;
                   13750:     }
                   13751: 
1.1062    droeschl 13752:     sub unique_library {
                   13753: 	#2x reverse removes all hostnames that appear more than once
                   13754:         my %unique = reverse &all_library();
                   13755:         return reverse %unique;
                   13756:     }
                   13757: 
1.841     albertel 13758:     sub get_servers {
1.852     albertel 13759: 	&load_hosts_tab() if (!$loaded);
                   13760: 
1.841     albertel 13761: 	my ($domain,$type) = @_;
                   13762: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13763: 	                                          : %hostname;
                   13764: 	my %result;
1.842     albertel 13765: 	if (ref($domain) eq 'ARRAY') {
                   13766: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13767: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13768: 		    $result{$host} = $hostname;
                   13769: 		}
                   13770: 	    }
                   13771: 	} else {
                   13772: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13773: 		if ($hostdom{$host} eq $domain) {
                   13774: 		    $result{$host} = $hostname;
                   13775: 		}
1.841     albertel 13776: 	    }
                   13777: 	}
                   13778: 	return %result;
                   13779:     }
1.845     albertel 13780: 
1.1062    droeschl 13781:     sub get_unique_servers {
                   13782:         my %unique = reverse &get_servers(@_);
                   13783: 	return reverse %unique;
                   13784:     }
                   13785: 
1.844     albertel 13786:     sub host_domain {
1.852     albertel 13787: 	&load_hosts_tab() if (!$loaded);
                   13788: 
1.844     albertel 13789: 	my ($lonid) = @_;
                   13790: 	return $hostdom{$lonid};
                   13791:     }
                   13792: 
1.841     albertel 13793:     sub all_domains {
1.852     albertel 13794: 	&load_hosts_tab() if (!$loaded);
                   13795: 
1.841     albertel 13796: 	my %seen;
                   13797: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13798: 	return @uniq;
                   13799:     }
1.1074    raeburn  13800: 
                   13801:     sub internet_dom {
                   13802:         &load_hosts_tab() if (!$loaded);
                   13803: 
                   13804:         my ($lonid) = @_;
                   13805:         return $internetdom{$lonid};
                   13806:     }
1.1107    raeburn  13807: 
                   13808:     sub is_LC_dns {
                   13809:         &load_hosts_tab() if (!$loaded);
                   13810: 
                   13811:         my ($hostname) = @_;
                   13812:         return exists($LC_dns_serv{$hostname});
                   13813:     }
                   13814: 
1.1       albertel 13815: }
                   13816: 
1.847     albertel 13817: { 
                   13818:     my %iphost;
1.856     albertel 13819:     my %name_to_ip;
                   13820:     my %lonid_to_ip;
1.869     albertel 13821: 
1.847     albertel 13822:     sub get_hosts_from_ip {
                   13823: 	my ($ip) = @_;
                   13824: 	my %iphosts = &get_iphost();
                   13825: 	if (ref($iphosts{$ip})) {
                   13826: 	    return @{$iphosts{$ip}};
                   13827: 	}
                   13828: 	return;
1.839     albertel 13829:     }
1.864     albertel 13830:     
                   13831:     sub reset_hosts_ip_info {
                   13832: 	undef(%iphost);
                   13833: 	undef(%name_to_ip);
                   13834: 	undef(%lonid_to_ip);
                   13835:     }
1.856     albertel 13836: 
                   13837:     sub get_host_ip {
                   13838: 	my ($lonid) = @_;
                   13839: 	if (exists($lonid_to_ip{$lonid})) {
                   13840: 	    return $lonid_to_ip{$lonid};
                   13841: 	}
                   13842: 	my $name=&hostname($lonid);
                   13843:    	my $ip = gethostbyname($name);
                   13844: 	return if (!$ip || length($ip) ne 4);
                   13845: 	$ip=inet_ntoa($ip);
                   13846: 	$name_to_ip{$name}   = $ip;
                   13847: 	$lonid_to_ip{$lonid} = $ip;
                   13848: 	return $ip;
                   13849:     }
1.847     albertel 13850:     
                   13851:     sub get_iphost {
1.1172.2.70  raeburn  13852: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13853: 
1.869     albertel 13854: 	if (!$ignore_cache) {
                   13855: 	    if (%iphost) {
                   13856: 		return %iphost;
                   13857: 	    }
                   13858: 	    my ($ip_info,$cached)=
                   13859: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13860: 	    if ($cached) {
                   13861: 		%iphost      = %{$ip_info->[0]};
                   13862: 		%name_to_ip  = %{$ip_info->[1]};
                   13863: 		%lonid_to_ip = %{$ip_info->[2]};
                   13864: 		return %iphost;
                   13865: 	    }
                   13866: 	}
1.894     albertel 13867: 
                   13868: 	# get yesterday's info for fallback
                   13869: 	my %old_name_to_ip;
                   13870: 	my ($ip_info,$cached)=
                   13871: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13872: 	if ($cached) {
                   13873: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13874: 	}
                   13875: 
1.1172.2.70  raeburn  13876: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13877: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13878: 	    my $ip;
                   13879: 	    if (!exists($name_to_ip{$name})) {
                   13880: 		$ip = gethostbyname($name);
                   13881: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13882: 		    if (defined($old_name_to_ip{$name})) {
                   13883: 			$ip = $old_name_to_ip{$name};
                   13884: 			&logthis("Can't find $name defaulting to old $ip");
                   13885: 		    } else {
                   13886: 			&logthis("Name $name no IP found");
                   13887: 			next;
                   13888: 		    }
                   13889: 		} else {
                   13890: 		    $ip=inet_ntoa($ip);
1.847     albertel 13891: 		}
                   13892: 		$name_to_ip{$name} = $ip;
                   13893: 	    } else {
                   13894: 		$ip = $name_to_ip{$name};
1.653     albertel 13895: 	    }
1.888     albertel 13896: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13897: 		$lonid_to_ip{$id} = $ip;
                   13898: 	    }
                   13899: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13900: 	}
1.1172.2.70  raeburn  13901:         unless ($nocache) {
                   13902: 	    &do_cache_new('iphost','iphost',
                   13903: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13904: 		          48*60*60);
                   13905:         }
1.869     albertel 13906: 
1.847     albertel 13907: 	return %iphost;
1.598     albertel 13908:     }
                   13909: 
1.992     raeburn  13910:     #
                   13911:     #  Given a DNS returns the loncapa host name for that DNS 
                   13912:     # 
                   13913:     sub host_from_dns {
                   13914:         my ($dns) = @_;
                   13915:         my @hosts;
                   13916:         my $ip;
                   13917: 
1.993     raeburn  13918:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13919:             $ip = $name_to_ip{$dns};
                   13920:         }
                   13921:         if (!$ip) {
                   13922:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13923:             if (length($ip) == 4) { 
                   13924: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13925:             }
                   13926:         }
                   13927:         if ($ip) {
                   13928: 	    @hosts = get_hosts_from_ip($ip);
                   13929: 	    return $hosts[0];
                   13930:         }
                   13931:         return undef;
1.986     foxr     13932:     }
1.992     raeburn  13933: 
1.1074    raeburn  13934:     sub get_internet_names {
                   13935:         my ($lonid) = @_;
                   13936:         return if ($lonid eq '');
                   13937:         my ($idnref,$cached)=
                   13938:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13939:         if ($cached) {
                   13940:             return $idnref;
                   13941:         }
                   13942:         my $ip = &get_host_ip($lonid);
                   13943:         my @hosts = &get_hosts_from_ip($ip);
                   13944:         my %iphost = &get_iphost();
                   13945:         my (@idns,%seen);
                   13946:         foreach my $id (@hosts) {
                   13947:             my $dom = &host_domain($id);
                   13948:             my $prim_id = &domain($dom,'primary');
                   13949:             my $prim_ip = &get_host_ip($prim_id);
                   13950:             next if ($seen{$prim_ip});
                   13951:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13952:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13953:                     my $intdom = &internet_dom($id);
                   13954:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13955:                         push(@idns,$intdom);
                   13956:                     }
                   13957:                 }
                   13958:             }
                   13959:             $seen{$prim_ip} = 1;
                   13960:         }
1.1172.2.23  raeburn  13961:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13962:     }
                   13963: 
1.986     foxr     13964: }
                   13965: 
1.1079    raeburn  13966: sub all_loncaparevs {
1.1172.2.39  raeburn  13967:     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  13968: }
                   13969: 
1.1172.2.27  raeburn  13970: # ------------------------------------------------------- Read loncaparev table
                   13971: {
                   13972:     sub load_loncaparevs {
                   13973:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13974:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13975:                 while (my $configline=<$config>) {
                   13976:                     chomp($configline);
                   13977:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13978:                     $loncaparevs{$hostid}=$loncaparev;
                   13979:                 }
                   13980:                 close($config);
                   13981:             }
                   13982:         }
                   13983:     }
                   13984: }
                   13985: 
                   13986: # ----------------------------------------------------- Read serverhostID table
                   13987: {
                   13988:     sub load_serverhomeIDs {
                   13989:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13990:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13991:                 while (my $configline=<$config>) {
                   13992:                     chomp($configline);
                   13993:                     my ($name,$id)=split(/:/,$configline);
                   13994:                     $serverhomeIDs{$name}=$id;
                   13995:                 }
                   13996:                 close($config);
                   13997:             }
                   13998:         }
                   13999:     }
                   14000: }
                   14001: 
                   14002: 
1.862     albertel 14003: BEGIN {
                   14004: 
                   14005: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14006:     unless ($readit) {
                   14007: {
                   14008:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14009:     %perlvar = (%perlvar,%{$configvars});
                   14010: }
                   14011: 
                   14012: 
1.1       albertel 14013: # ------------------------------------------------------ Read spare server file
                   14014: {
1.1172.2.96  raeburn  14015:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14016: 
                   14017:     while (my $configline=<$config>) {
                   14018:        chomp($configline);
1.284     matthew  14019:        if ($configline) {
1.784     albertel 14020: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14021: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14022: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14023:        }
                   14024:     }
1.448     albertel 14025:     close($config);
1.1       albertel 14026: }
1.11      www      14027: # ------------------------------------------------------------ Read permissions
                   14028: {
1.1172.2.96  raeburn  14029:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14030: 
                   14031:     while (my $configline=<$config>) {
1.448     albertel 14032: 	chomp($configline);
                   14033: 	if ($configline) {
                   14034: 	    my ($role,$perm)=split(/ /,$configline);
                   14035: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14036: 	}
1.11      www      14037:     }
1.448     albertel 14038:     close($config);
1.11      www      14039: }
                   14040: 
                   14041: # -------------------------------------------- Read plain texts for permissions
                   14042: {
1.1172.2.96  raeburn  14043:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14044: 
                   14045:     while (my $configline=<$config>) {
1.448     albertel 14046: 	chomp($configline);
                   14047: 	if ($configline) {
1.742     raeburn  14048: 	    my ($short,@plain)=split(/:/,$configline);
                   14049:             %{$prp{$short}} = ();
                   14050: 	    if (@plain > 0) {
                   14051:                 $prp{$short}{'std'} = $plain[0];
                   14052:                 for (my $i=1; $i<@plain; $i++) {
                   14053:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14054:                 }
                   14055:             }
1.448     albertel 14056: 	}
1.135     www      14057:     }
1.448     albertel 14058:     close($config);
1.135     www      14059: }
                   14060: 
                   14061: # ---------------------------------------------------------- Read package table
                   14062: {
1.1172.2.96  raeburn  14063:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14064: 
                   14065:     while (my $configline=<$config>) {
1.483     albertel 14066: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14067: 	chomp($configline);
                   14068: 	my ($short,$plain)=split(/:/,$configline);
                   14069: 	my ($pack,$name)=split(/\&/,$short);
                   14070: 	if ($plain ne '') {
                   14071: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14072: 	    $packagetab{$short}=$plain; 
                   14073: 	}
1.11      www      14074:     }
1.448     albertel 14075:     close($config);
1.329     matthew  14076: }
                   14077: 
1.1172.2.27  raeburn  14078: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14079: 
1.1172.2.27  raeburn  14080: &load_loncaparevs();
                   14081: 
                   14082: # ------------------------------------------------------- Read serverhostID table
                   14083: 
                   14084: &load_serverhomeIDs();
1.1074    raeburn  14085: 
1.1172.2.27  raeburn  14086: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14087: {
                   14088:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14089:     if (-e $file) {
                   14090:         my $parser = HTML::LCParser->new($file);
                   14091:         while (my $token = $parser->get_token()) {
                   14092:             if ($token->[0] eq 'S') {
                   14093:                 my $item = $token->[1];
                   14094:                 my $name = $token->[2]{'name'};
                   14095:                 my $value = $token->[2]{'value'};
                   14096:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14097:                     my $release = $parser->get_text();
                   14098:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14099:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14100:                 }
                   14101:             }
                   14102:         }
                   14103:     }
1.1073    raeburn  14104: }
                   14105: 
1.1138    raeburn  14106: # ---------------------------------------------------------- Read managers table
                   14107: {
                   14108:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14109:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14110:             while (my $configline=<$config>) {
                   14111:                 chomp($configline);
                   14112:                 next if ($configline =~ /^\#/);
                   14113:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14114:                     $managerstab{$configline} = 1;
                   14115:                 }
                   14116:             }
                   14117:             close($config);
                   14118:         }
                   14119:     }
                   14120: }
                   14121: 
1.329     matthew  14122: # ------------- set up temporary directory
                   14123: {
1.1117    foxr     14124:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14125: 
1.11      www      14126: }
                   14127: 
1.1172.2.104  raeburn  14128: # ------------- set default texengine (domain default overrides this)
                   14129: {
                   14130:     $deftex = LONCAPA::texengine();
                   14131: }
                   14132: 
1.1172.2.114  raeburn  14133: # ------------- set default minimum length for passwords for internal auth users
                   14134: {
                   14135:     $passwdmin = LONCAPA::passwd_min();
                   14136: }
                   14137: 
1.794     albertel 14138: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14139: 				'compress_threshold'=> 20_000,
                   14140:  			        });
1.185     www      14141: 
1.281     www      14142: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14143: $dumpcount=0;
1.958     www      14144: $locknum=0;
1.22      www      14145: 
1.163     harris41 14146: &logtouch();
1.672     albertel 14147: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14148: $readit=1;
1.564     albertel 14149:     {
                   14150: 	use integer;
                   14151: 	my $test=(2**32)+1;
1.568     albertel 14152: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14153: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14154:     }
1.195     www      14155: }
1.1       albertel 14156: }
1.179     www      14157: 
1.1       albertel 14158: 1;
1.191     harris41 14159: __END__
                   14160: 
1.243     albertel 14161: =pod
                   14162: 
1.191     harris41 14163: =head1 NAME
                   14164: 
1.243     albertel 14165: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14166: 
                   14167: =head1 SYNOPSIS
                   14168: 
1.243     albertel 14169: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14170: 
                   14171:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14172: 
1.243     albertel 14173: Common parameters:
                   14174: 
                   14175: =over 4
                   14176: 
                   14177: =item *
                   14178: 
                   14179: $uname : an internal username (if $cname expecting a course Id specifically)
                   14180: 
                   14181: =item *
                   14182: 
                   14183: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14184: 
                   14185: =item *
                   14186: 
                   14187: $symb : a resource instance identifier
                   14188: 
                   14189: =item *
                   14190: 
                   14191: $namespace : the name of a .db file that contains the data needed or
                   14192: being set.
                   14193: 
                   14194: =back
                   14195: 
1.394     bowersj2 14196: =head1 OVERVIEW
1.191     harris41 14197: 
1.394     bowersj2 14198: lonnet provides subroutines which interact with the
                   14199: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14200: about classes, users, and resources.
1.243     albertel 14201: 
                   14202: For many of these objects you can also use this to store data about
                   14203: them or modify them in various ways.
1.191     harris41 14204: 
1.394     bowersj2 14205: =head2 Symbs
1.191     harris41 14206: 
1.394     bowersj2 14207: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14208: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14209: map, the resource number of the resource in the map, and the URL of
                   14210: the resource itself. The latter is somewhat redundant, but might help
                   14211: if maps change.
                   14212: 
                   14213: An example is
                   14214: 
                   14215:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14216: 
                   14217: The respective map entry is
                   14218: 
                   14219:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14220:   title="Problem 2">
                   14221:  </resource>
                   14222: 
                   14223: Symbs are used by the random number generator, as well as to store and
                   14224: restore data specific to a certain instance of for example a problem.
                   14225: 
                   14226: =head2 Storing And Retrieving Data
                   14227: 
                   14228: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14229: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14230: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14231: is is the non-critical message twin of cstore. These functions are for
                   14232: handlers to store a perl hash to a user's permanent data space in an
                   14233: easy manner, and to retrieve it again on another call. It is expected
                   14234: that a handler would use this once at the beginning to retrieve data,
                   14235: and then again once at the end to send only the new data back.
                   14236: 
                   14237: The data is stored in the user's data directory on the user's
                   14238: homeserver under the ID of the course.
                   14239: 
                   14240: The hash that is returned by restore will have all of the previous
                   14241: value for all of the elements of the hash.
                   14242: 
                   14243: Example:
                   14244: 
                   14245:  #creating a hash
                   14246:  my %hash;
                   14247:  $hash{'foo'}='bar';
                   14248: 
                   14249:  #storing it
                   14250:  &Apache::lonnet::cstore(\%hash);
                   14251: 
                   14252:  #changing a value
                   14253:  $hash{'foo'}='notbar';
                   14254: 
                   14255:  #adding a new value
                   14256:  $hash{'bar'}='foo';
                   14257:  &Apache::lonnet::cstore(\%hash);
                   14258: 
                   14259:  #retrieving the hash
                   14260:  my %history=&Apache::lonnet::restore();
                   14261: 
                   14262:  #print the hash
                   14263:  foreach my $key (sort(keys(%history))) {
                   14264:    print("\%history{$key} = $history{$key}");
                   14265:  }
                   14266: 
                   14267: Will print out:
1.191     harris41 14268: 
1.394     bowersj2 14269:  %history{1:foo} = bar
                   14270:  %history{1:keys} = foo:timestamp
                   14271:  %history{1:timestamp} = 990455579
                   14272:  %history{2:bar} = foo
                   14273:  %history{2:foo} = notbar
                   14274:  %history{2:keys} = foo:bar:timestamp
                   14275:  %history{2:timestamp} = 990455580
                   14276:  %history{bar} = foo
                   14277:  %history{foo} = notbar
                   14278:  %history{timestamp} = 990455580
                   14279:  %history{version} = 2
                   14280: 
                   14281: Note that the special hash entries C<keys>, C<version> and
                   14282: C<timestamp> were added to the hash. C<version> will be equal to the
                   14283: total number of versions of the data that have been stored. The
                   14284: C<timestamp> attribute will be the UNIX time the hash was
                   14285: stored. C<keys> is available in every historical section to list which
                   14286: keys were added or changed at a specific historical revision of a
                   14287: hash.
                   14288: 
                   14289: B<Warning>: do not store the hash that restore returns directly. This
                   14290: will cause a mess since it will restore the historical keys as if the
                   14291: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14292: 
1.394     bowersj2 14293: Calling convention:
1.191     harris41 14294: 
1.1172.2.27  raeburn  14295:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14296:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14297: 
1.394     bowersj2 14298: For more detailed information, see lonnet specific documentation.
1.191     harris41 14299: 
1.394     bowersj2 14300: =head1 RETURN MESSAGES
1.191     harris41 14301: 
1.394     bowersj2 14302: =over 4
1.191     harris41 14303: 
1.394     bowersj2 14304: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14305: 
1.394     bowersj2 14306: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14307: when the connection is brought back up
1.191     harris41 14308: 
1.394     bowersj2 14309: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14310: for later delivery
1.191     harris41 14311: 
1.967     bisitz   14312: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14313: 
1.394     bowersj2 14314: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14315: that was requested
1.191     harris41 14316: 
1.243     albertel 14317: =back
1.191     harris41 14318: 
1.243     albertel 14319: =head1 PUBLIC SUBROUTINES
1.191     harris41 14320: 
1.243     albertel 14321: =head2 Session Environment Functions
1.191     harris41 14322: 
1.243     albertel 14323: =over 4
1.191     harris41 14324: 
1.394     bowersj2 14325: =item * 
                   14326: X<appenv()>
1.949     raeburn  14327: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14328: the user envirnoment file, and will be restored for each access this
1.620     albertel 14329: user makes during this session, also modifies the %env for the current
1.949     raeburn  14330: process. Optional rolesarrayref - if defined contains a reference to an array
                   14331: of roles which are exempt from the restriction on modifying user.role entries 
                   14332: in the user's environment.db and in %env.    
1.191     harris41 14333: 
                   14334: =item *
1.394     bowersj2 14335: X<delenv()>
1.987     raeburn  14336: B<delenv($delthis,$regexp)>: removes all items from the session
                   14337: environment file that begin with $delthis. If the 
                   14338: optional second arg - $regexp - is true, $delthis is treated as a 
                   14339: regular expression, otherwise \Q$delthis\E is used. 
                   14340: The values are also deleted from the current processes %env.
1.191     harris41 14341: 
1.795     albertel 14342: =item * get_env_multiple($name) 
                   14343: 
                   14344: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14345: values may be defined and end up as an array ref.
                   14346: 
                   14347: returns an array of values
                   14348: 
1.243     albertel 14349: =back
                   14350: 
                   14351: =head2 User Information
1.191     harris41 14352: 
1.243     albertel 14353: =over 4
1.191     harris41 14354: 
                   14355: =item *
1.394     bowersj2 14356: X<queryauthenticate()>
                   14357: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14358: authentication scheme
                   14359: 
                   14360: =item *
1.394     bowersj2 14361: X<authenticate()>
1.1073    raeburn  14362: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14363: authenticate user from domain's lib servers (first use the current
                   14364: one). C<$upass> should be the users password.
1.1073    raeburn  14365: $checkdefauth is optional (value is 1 if a check should be made to
                   14366:    authenticate user using default authentication method, and allow
                   14367:    account creation if username does not have account in the domain).
                   14368: $clientcancheckhost is optional (value is 1 if checking whether the
                   14369:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14370: 
                   14371: =item *
1.394     bowersj2 14372: X<homeserver()>
                   14373: B<homeserver($uname,$udom)>: find the server which has
                   14374: the user's directory and files (there must be only one), this caches
                   14375: the answer, and also caches if there is a borken connection.
1.191     harris41 14376: 
                   14377: =item *
1.394     bowersj2 14378: X<idget()>
                   14379: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14380: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14381: username, and only 1 username per ID in a specific domain) (returns
                   14382: hash: id=>name,id=>name)
1.191     harris41 14383: 
                   14384: =item *
1.394     bowersj2 14385: X<idrget()>
                   14386: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14387: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14388: 
                   14389: =item *
1.394     bowersj2 14390: X<idput()>
                   14391: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14392: 
                   14393: =item *
1.394     bowersj2 14394: X<rolesinit()>
1.1169    droeschl 14395: B<rolesinit($udom,$username)>: get user privileges.
                   14396: returns user role, first access and timer interval hashes
1.243     albertel 14397: 
                   14398: =item *
1.1171    droeschl 14399: X<privileged()>
                   14400: B<privileged($username,$domain)>: returns a true if user has a
                   14401: privileged and active role (i.e. su or dc), false otherwise.
                   14402: 
                   14403: =item *
1.551     albertel 14404: X<getsection()>
                   14405: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14406: course $cname, return section name/number or '' for "not in course"
                   14407: and '-1' for "no section"
                   14408: 
                   14409: =item *
1.394     bowersj2 14410: X<userenvironment()>
                   14411: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14412: passed in @what from the requested user's environment, returns a hash
                   14413: 
1.858     raeburn  14414: =item * 
                   14415: X<userlog_query()>
1.859     albertel 14416: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14417: activity.log file. %filters defines filters applied when parsing the
                   14418: log file. These can be start or end timestamps, or the type of action
                   14419: - log to look for Login or Logout events, check for Checkin or
                   14420: Checkout, role for role selection. The response is in the form
                   14421: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14422: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14423: 
1.243     albertel 14424: =back
                   14425: 
                   14426: =head2 User Roles
                   14427: 
                   14428: =over 4
                   14429: 
                   14430: =item *
                   14431: 
1.1172.2.65  raeburn  14432: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14433: returns codes for allowed actions.
                   14434: 
                   14435: The first argument is required, all others are optional.
                   14436: 
                   14437: $priv is the privilege being checked.
                   14438: $uri contains additional information about what is being checked for access (e.g.,
                   14439: URL, course ID etc.).
                   14440: $symb is the unique resource instance identifier in a course; if needed,
                   14441: but not provided, it will be retrieved via a call to &symbread().
                   14442: $role is the role for which a priv is being checked (only used if priv is evb).
                   14443: $clientip is the user's IP address (only used when checking for access to portfolio
                   14444: files).
                   14445: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14446: prevents recursive calls to &allowed.
                   14447: 
1.243     albertel 14448:  F: full access
                   14449:  U,I,K: authentication modes (cxx only)
                   14450:  '': forbidden
                   14451:  1: user needs to choose course
                   14452:  2: browse allowed
1.766     albertel 14453:  A: passphrase authentication needed
1.1172.2.65  raeburn  14454:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14455: 
                   14456: =item *
                   14457: 
1.1172.2.13  raeburn  14458: constructaccess($url,$setpriv) : check for access to construction space URL
                   14459: 
                   14460: See if the owner domain and name in the URL match those in the
                   14461: expected environment.  If so, return three element list
                   14462: ($ownername,$ownerdomain,$ownerhome).
                   14463: 
                   14464: Otherwise return the null string.
                   14465: 
                   14466: If second argument 'setpriv' is true, it assigns the privileges,
                   14467: and returns the same three element list, unless the owner has
                   14468: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14469: in which case the null string is returned.
                   14470: 
                   14471: =item *
                   14472: 
1.1172.2.84  raeburn  14473: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14474: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14475: for system, domain, and course level. $uname and $udom are optional (current
                   14476: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14477: 
                   14478: =item *
                   14479: 
1.988     raeburn  14480: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14481: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14482: $type is Course (default) or Community.
1.988     raeburn  14483: If $forcedefault evaluates to true, text returned will be default 
                   14484: text for $type. Otherwise, if this is a course, the text returned 
                   14485: will be a custom name for the role (if defined in the course's 
                   14486: environment).  If no custom name is defined the default is returned.
                   14487:    
1.832     raeburn  14488: =item *
                   14489: 
1.1172.2.23  raeburn  14490: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14491: All arguments are optional. Returns a hash of a roles, either for
                   14492: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14493: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14494: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14495: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14496: For each key, value is set to colon-separated start and end times for
                   14497: the role.  If no username and domain are specified, will default to
1.934     raeburn  14498: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14499: of role statuses (active, future or previous), roles 
                   14500: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14501: to restrict the list of roles reported. If no array ref is 
                   14502: provided for types, will default to return only active roles.
1.834     albertel 14503: 
1.1172.2.13  raeburn  14504: =item *
                   14505: 
                   14506: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14507: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14508: 
                   14509: Additional optional arguments are: $type (if role checking is to be restricted
                   14510: to certain user status types -- previous (expired roles), active (currently
                   14511: available roles) or future (roles available in the future), and
                   14512: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14513: have active Domain Coordinator role in course's domain or in additional
                   14514: domains (specified in 'Domains to check for privileged users' in course
                   14515: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14516: 
                   14517: =item *
                   14518: 
                   14519: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14520: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14521: $possdomains and $possroles are optional array refs -- to domains to check and
                   14522: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14523: users' roles.db to check for a dc or su role in any domain. This can be
                   14524: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14525: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14526: this then allows &privileged_by_domain() to be used, which caches the identity
                   14527: of privileged users, eliminating the need for repeated calls to &dump().
                   14528: 
                   14529: =item *
                   14530: 
                   14531: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14532: where the outer hash keys are domains specified in the $possdomains array ref,
                   14533: next inner hash keys are privileged roles specified in the $roles array ref,
                   14534: and the innermost hash contains key = value pairs for username:domain = end:start
                   14535: for active or future "privileged" users with that role in that domain. To avoid
                   14536: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14537: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14538: 
1.243     albertel 14539: =back
                   14540: 
                   14541: =head2 User Modification
                   14542: 
                   14543: =over 4
                   14544: 
                   14545: =item *
                   14546: 
1.957     raeburn  14547: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14548: user for the level given by URL.  Optional start and end dates (leave empty
                   14549: string or zero for "no date")
1.191     harris41 14550: 
                   14551: =item *
                   14552: 
1.243     albertel 14553: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14554: change a users, password, possible return values are: ok,
                   14555: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14556: refused
1.191     harris41 14557: 
                   14558: =item *
                   14559: 
1.243     albertel 14560: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14561: 
                   14562: =item *
                   14563: 
1.1058    raeburn  14564: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14565:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14566: 
                   14567: will update user information (firstname,middlename,lastname,generation,
                   14568: permanentemail), and if forceid is true, student/employee ID also.
                   14569: A user's institutional affiliation(s) can also be updated.
                   14570: User information fields will not be overwritten with empty entries 
                   14571: unless the field is included in the $candelete array reference.
                   14572: This array is included when a single user is modified via "Manage Users",
                   14573: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14574: 
                   14575: =item *
                   14576: 
1.286     matthew  14577: modifystudent
                   14578: 
1.957     raeburn  14579: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14580: The course id is resolved based on the current user's environment.  
                   14581: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14582: associated with a course.
                   14583: 
1.297     matthew  14584: This call is essentially a wrapper for lonnet::modifyuser and
                   14585: lonnet::modify_student_enrollment
1.286     matthew  14586: 
                   14587: Inputs: 
                   14588: 
                   14589: =over 4
                   14590: 
1.957     raeburn  14591: =item B<$udom> Student's loncapa domain
1.286     matthew  14592: 
1.957     raeburn  14593: =item B<$uname> Student's loncapa login name
1.286     matthew  14594: 
1.964     bisitz   14595: =item B<$uid> Student/Employee ID
1.286     matthew  14596: 
1.957     raeburn  14597: =item B<$umode> Student's authentication mode
1.286     matthew  14598: 
1.957     raeburn  14599: =item B<$upass> Student's password
1.286     matthew  14600: 
1.957     raeburn  14601: =item B<$first> Student's first name
1.286     matthew  14602: 
1.957     raeburn  14603: =item B<$middle> Student's middle name
1.286     matthew  14604: 
1.957     raeburn  14605: =item B<$last> Student's last name
1.286     matthew  14606: 
1.957     raeburn  14607: =item B<$gene> Student's generation
1.286     matthew  14608: 
1.957     raeburn  14609: =item B<$usec> Student's section in course
1.286     matthew  14610: 
                   14611: =item B<$end> Unix time of the roles expiration
                   14612: 
                   14613: =item B<$start> Unix time of the roles start date
                   14614: 
                   14615: =item B<$forceid> If defined, allow $uid to be changed
                   14616: 
                   14617: =item B<$desiredhome> server to use as home server for student
                   14618: 
1.957     raeburn  14619: =item B<$email> Student's permanent e-mail address
                   14620: 
                   14621: =item B<$type> Type of enrollment (auto or manual)
                   14622: 
1.963     raeburn  14623: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14624: 
                   14625: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14626: 
1.963     raeburn  14627: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14628: 
1.963     raeburn  14629: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14630: 
1.1172.2.19  raeburn  14631: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14632: 
                   14633: =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  14634: 
1.286     matthew  14635: =back
1.297     matthew  14636: 
                   14637: =item *
                   14638: 
                   14639: modify_student_enrollment
                   14640: 
1.1172.2.31  raeburn  14641: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14642: 'role.request.course' must be defined for this function to proceed.
                   14643: 
                   14644: Inputs:
                   14645: 
                   14646: =over 4
                   14647: 
1.1172.2.31  raeburn  14648: =item $udom, student's domain
1.297     matthew  14649: 
1.1172.2.31  raeburn  14650: =item $uname, student's name
1.297     matthew  14651: 
1.1172.2.31  raeburn  14652: =item $uid, student's user id
1.297     matthew  14653: 
1.1172.2.31  raeburn  14654: =item $first, student's first name
1.297     matthew  14655: 
                   14656: =item $middle
                   14657: 
                   14658: =item $last
                   14659: 
                   14660: =item $gene
                   14661: 
                   14662: =item $usec
                   14663: 
                   14664: =item $end
                   14665: 
                   14666: =item $start
                   14667: 
1.957     raeburn  14668: =item $type
                   14669: 
                   14670: =item $locktype
                   14671: 
                   14672: =item $cid
                   14673: 
                   14674: =item $selfenroll
                   14675: 
                   14676: =item $context
                   14677: 
1.1172.2.19  raeburn  14678: =item $credits, number of credits student will earn from this class
                   14679: 
1.1172.2.76  raeburn  14680: =item $instsec, institutional course section code for student
                   14681: 
1.297     matthew  14682: =back
                   14683: 
1.191     harris41 14684: 
                   14685: =item *
                   14686: 
1.243     albertel 14687: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14688: custom role; give a custom role to a user for the level given by URL.  Specify
                   14689: name and domain of role author, and role name
1.191     harris41 14690: 
                   14691: =item *
                   14692: 
1.243     albertel 14693: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14694: 
                   14695: =item *
                   14696: 
1.243     albertel 14697: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14698: 
                   14699: =back
                   14700: 
                   14701: =head2 Course Infomation
                   14702: 
                   14703: =over 4
1.191     harris41 14704: 
                   14705: =item *
                   14706: 
1.1118    foxr     14707: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14708: specified course id, including all environment settings for the
                   14709: course, the description of the course will be in the hash under the
                   14710: key 'description'
1.191     harris41 14711: 
1.1118    foxr     14712: $options is an optional parameter that if supplied is a hash reference that controls
                   14713: what how this function works.  It has the following key/values:
                   14714: 
                   14715: =over 4
                   14716: 
                   14717: =item freshen_cache
                   14718: 
                   14719: If defined, and the environment cache for the course is valid, it is 
                   14720: returned in the returned hash.
                   14721: 
                   14722: =item one_time
                   14723: 
                   14724: If defined, the last cache time is set to _now_
                   14725: 
                   14726: =item user
                   14727: 
                   14728: If defined, the supplied username is used instead of the current user.
                   14729: 
                   14730: 
                   14731: =back
                   14732: 
1.191     harris41 14733: =item *
                   14734: 
1.624     albertel 14735: resdata($name,$domain,$type,@which) : request for current parameter
                   14736: setting for a specific $type, where $type is either 'course' or 'user',
                   14737: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14738: answers for 10 minutes.
1.243     albertel 14739: 
1.877     foxr     14740: =item *
                   14741: 
                   14742: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14743: data base, returning a hash that is keyed by the resource name and has
                   14744: values that are the resource value.  I believe that the timestamps and
                   14745: versions are also returned.
                   14746: 
1.1172.2.31  raeburn  14747: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14748: supplemental content area. This routine caches the number of files for
                   14749: 10 minutes.
                   14750: 
1.243     albertel 14751: =back
                   14752: 
                   14753: =head2 Course Modification
                   14754: 
                   14755: =over 4
1.191     harris41 14756: 
                   14757: =item *
                   14758: 
1.243     albertel 14759: writecoursepref($courseid,%prefs) : write preferences (environment
                   14760: database) for a course
1.191     harris41 14761: 
                   14762: =item *
                   14763: 
1.1011    raeburn  14764: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14765: 
                   14766: =item *
                   14767: 
1.1038    raeburn  14768: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14769: 
1.1167    droeschl 14770: =item *
                   14771: 
                   14772: is_course($courseid), is_course($cdom, $cnum)
                   14773: 
                   14774: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14775: two component version $cdom, $cnum. It checks if the specified course exists.
                   14776: 
                   14777: Returns:
                   14778:     undef if the course doesn't exist, otherwise
                   14779:     in scalar context the combined courseid.
                   14780:     in list context the two components of the course identifier, domain and 
                   14781:     courseid.    
                   14782: 
1.243     albertel 14783: =back
                   14784: 
1.1172.2.109  raeburn  14785: =head2 Bubblesheet Configuration
                   14786: 
                   14787: =over 4
                   14788: 
                   14789: =item *
                   14790: 
                   14791: get_scantron_config($which)
                   14792: 
                   14793: $which - the name of the configuration to parse from the file.
                   14794: 
                   14795: Parses and returns the bubblesheet configuration line selected as a
                   14796: hash of configuration file fields.
                   14797: 
                   14798: 
                   14799: Returns:
                   14800:     If the named configuration is not in the file, an empty
                   14801:     hash is returned.
                   14802: 
                   14803:     a hash with the fields
                   14804:       name         - internal name for the this configuration setup
                   14805:       description  - text to display to operator that describes this config
                   14806:       CODElocation - if 0 or the string 'none'
                   14807:                           - no CODE exists for this config
                   14808:                      if -1 || the string 'letter'
                   14809:                           - a CODE exists for this config and is
                   14810:                             a string of letters
                   14811:                      Unsupported value (but planned for future support)
                   14812:                           if a positive integer
                   14813:                                - The CODE exists as the first n items from
                   14814:                                  the question section of the form
                   14815:                           if the string 'number'
                   14816:                                - The CODE exists for this config and is
                   14817:                                  a string of numbers
                   14818:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14819:                      the CODE starts
                   14820:       CODElength  - length of the CODE
                   14821:       IDstart     - column where the student/employee ID starts
                   14822:       IDlength    - length of the student/employee ID info
                   14823:       Qstart      - column where the information from the bubbled
                   14824:                     'questions' start
                   14825:       Qlength     - number of columns comprising a single bubble line from
                   14826:                     the sheet. (usually either 1 or 10)
                   14827:       Qon         - either a single character representing the character used
                   14828:                     to signal a bubble was chosen in the positional setup, or
                   14829:                     the string 'letter' if the letter of the chosen bubble is
                   14830:                     in the final, or 'number' if a number representing the
                   14831:                     chosen bubble is in the file (1->A 0->J)
                   14832:       Qoff        - the character used to represent that a bubble was
                   14833:                     left blank
                   14834:       PaperID     - if the scanning process generates a unique number for each
                   14835:                     sheet scanned the column that this ID number starts in
                   14836:       PaperIDlength - number of columns that comprise the unique ID number
                   14837:                       for the sheet of paper
                   14838:       FirstName   - column that the first name starts in
                   14839:       FirstNameLength - number of columns that the first name spans
                   14840:       LastName    - column that the last name starts in
                   14841:       LastNameLength - number of columns that the last name spans
                   14842:       BubblesPerRow - number of bubbles available in each row used to
                   14843:                       bubble an answer. (If not specified, 10 assumed).
                   14844: 
                   14845: 
                   14846: =item *
                   14847: 
                   14848: get_scantronformat_file($cdom)
                   14849: 
                   14850: $cdom - the course's domain (optional); if not supplied, uses
                   14851: domain for current $env{'request.course.id'}.
                   14852: 
                   14853: Returns an array containing lines from the scantron format file for
                   14854: the domain of the course.
                   14855: 
                   14856: If a url for a custom.tab file is listed in domain's configuration.db,
                   14857: lines are from this file.
                   14858: 
                   14859: Otherwise, if a default.tab has been published in RES space by the
                   14860: domainconfig user, lines are from this file.
                   14861: 
                   14862: Otherwise, fall back to getting lines from the legacy file on the
                   14863: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14864: 
                   14865: =back
                   14866: 
1.243     albertel 14867: =head2 Resource Subroutines
                   14868: 
                   14869: =over 4
1.191     harris41 14870: 
                   14871: =item *
                   14872: 
1.243     albertel 14873: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14874: 
                   14875: =item *
                   14876: 
1.243     albertel 14877: repcopy($filename) : subscribes to the requested file, and attempts to
                   14878: replicate from the owning library server, Might return
1.607     raeburn  14879: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14880: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14881: resource. Expects the local filesystem pathname
                   14882: (/home/httpd/html/res/....)
                   14883: 
                   14884: =back
                   14885: 
                   14886: =head2 Resource Information
                   14887: 
                   14888: =over 4
1.191     harris41 14889: 
                   14890: =item *
                   14891: 
1.1172.2.28  raeburn  14892: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14893: and returns the value of a variety of different possible values,
                   14894: $varname should be a request string, and the other parameters can be
                   14895: used to specify who and what one is asking about. Ordinarily, $cid 
                   14896: does not need to be specified, as it is retrived from 
                   14897: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14898: within lonuserstate::loadmap() when initializing a course, before
                   14899: $env{'request.course.id'} has been set, so it needs to be provided
                   14900: in that one case.
1.243     albertel 14901: 
                   14902: Possible values for $varname are environment.lastname (or other item
                   14903: from the envirnment hash), user.name (or someother aspect about the
                   14904: user), resource.0.maxtries (or some other part and parameter of a
                   14905: resource)
1.204     albertel 14906: 
                   14907: =item *
                   14908: 
1.243     albertel 14909: directcondval($number) : get current value of a condition; reads from a state
                   14910: string
1.204     albertel 14911: 
                   14912: =item *
                   14913: 
1.243     albertel 14914: condval($condidx) : value of condition index based on state
1.204     albertel 14915: 
                   14916: =item *
                   14917: 
1.243     albertel 14918: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14919: resource's metadata, $what should be either a specific key, or either
                   14920: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14921: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14922: 
                   14923: this function automatically caches all requests
1.191     harris41 14924: 
                   14925: =item *
                   14926: 
1.243     albertel 14927: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14928: network of library servers; returns file handle of where SQL and regex results
                   14929: will be stored for query
1.191     harris41 14930: 
                   14931: =item *
                   14932: 
1.1172.2.66  raeburn  14933: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14934: return symbolic list entry (all arguments optional).
                   14935: 
                   14936: Args: filename is the filename (including path) for the file for which a symb
                   14937: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14938: to check access status if more than one resource was found in the bighash
                   14939: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14940: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14941: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14942: cause possible symbs to be checked to determine if they are subject to content
                   14943: blocking, if so they will not be included as possible symbs; possibles is a
                   14944: ref to a hash, which, as a side effect, will be populated with all possible
                   14945: symbs (content blocking not tested).
                   14946: 
1.243     albertel 14947: returns the data handle
1.191     harris41 14948: 
                   14949: =item *
                   14950: 
1.1172.2.17  raeburn  14951: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14952: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14953: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14954: on failure, user must be in a course, as it assumes the existence of
                   14955: the course initial hash, and uses $env('request.course.id'}.  The third
                   14956: arg is an optional reference to a scalar.  If this arg is passed in the
                   14957: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14958: encrypted; otherwise it will be null.
1.243     albertel 14959: 
1.191     harris41 14960: =item *
                   14961: 
1.243     albertel 14962: symbclean($symb) : removes versions numbers from a symb, returns the
                   14963: cleaned symb
1.191     harris41 14964: 
                   14965: =item *
                   14966: 
1.243     albertel 14967: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14968: course map, user must be in a course for it to work.
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.243     albertel 14972: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14973: 
                   14974: =item *
                   14975: 
1.243     albertel 14976: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14977: a random seed, all arguments are optional, if they aren't sent it uses the
                   14978: environment to derive them. Note: if symb isn't sent and it can't get one
                   14979: from &symbread it will use the current time as its return value
1.191     harris41 14980: 
                   14981: =item *
                   14982: 
1.243     albertel 14983: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14984: unfakeable, receipt
1.191     harris41 14985: 
                   14986: =item *
                   14987: 
1.620     albertel 14988: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14989: 
                   14990: =item *
                   14991: 
1.243     albertel 14992: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14993: 
                   14994: =item *
                   14995: 
1.243     albertel 14996: 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 14997: 
                   14998: =item *
                   14999: 
1.243     albertel 15000: 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 15001: 
                   15002: =item *
                   15003: 
1.243     albertel 15004: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15005: 
                   15006: =item *
                   15007: 
1.243     albertel 15008: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15009: forcing spreadsheet to reevaluate the resource scores next time.
                   15010: 
1.1172.2.13  raeburn  15011: =item *
                   15012: 
                   15013: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15014: when viewing in course context.
                   15015: 
                   15016:  input: six args -- filename (decluttered), course number, course domain,
                   15017:                     url, symb (if registered) and group (if this is a
                   15018:                     group item -- e.g., bulletin board, group page etc.).
                   15019: 
                   15020:  output: array of five scalars --
                   15021:          $cfile -- url for file editing if editable on current server
                   15022:          $home -- homeserver of resource (i.e., for author if published,
                   15023:                                           or course if uploaded.).
                   15024:          $switchserver --  1 if server switch will be needed.
                   15025:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15026:          $forceview -- 1 if icon/link should be to go to view mode
                   15027: 
                   15028: =item *
                   15029: 
                   15030: is_course_upload($file,$cnum,$cdom)
                   15031: 
                   15032: Used in course context to determine if current file was uploaded to
                   15033: the course (i.e., would be found in /userfiles/docs on the course's
                   15034: homeserver.
                   15035: 
                   15036:   input: 3 args -- filename (decluttered), course number and course domain.
                   15037:   output: boolean -- 1 if file was uploaded.
                   15038: 
1.243     albertel 15039: =back
                   15040: 
                   15041: =head2 Storing/Retreiving Data
                   15042: 
                   15043: =over 4
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.1172.2.64  raeburn  15047: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15048: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15049: the remaining args aren't required and if they aren't passed or are '' they will
                   15050: be derived from the env (with the exception of $laststore, which is an
                   15051: optional arg used when a user's submission is stored in grading).
                   15052: $laststore is $version=$timestamp, where $version is the most recent version
                   15053: number retrieved for the corresponding $symb in the $namespace db file, and
                   15054: $timestamp is the timestamp for that transaction (UNIX time).
                   15055: $laststore is currently only passed when cstore() is called by
                   15056: structuretags::finalize_storage().
1.191     harris41 15057: 
                   15058: =item *
                   15059: 
1.1172.2.64  raeburn  15060: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15061: but uses critical subroutine
1.191     harris41 15062: 
                   15063: =item *
                   15064: 
1.243     albertel 15065: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15066: all args are optional
1.191     harris41 15067: 
                   15068: =item *
                   15069: 
1.717     albertel 15070: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15071: dumps the complete (or key matching regexp) namespace into a hash
                   15072: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15073: normally &store()ed into
                   15074: 
                   15075: $range should be either an integer '100' (give me the first 100
                   15076:                                            matching records)
                   15077:               or be  two integers sperated by a - with no spaces
                   15078:                  '30-50' (give me the 30th through the 50th matching
                   15079:                           records)
                   15080: 
                   15081: 
                   15082: =item *
                   15083: 
1.1172.2.59  raeburn  15084: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15085: replaces a &store() version of data with a replacement set of data
                   15086: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15087: reference. If $tolog is true, the transaction is logged in the courselog
                   15088: with an action=PUTSTORE.
1.717     albertel 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15093: works very similar to store/cstore, but all data is stored in a
                   15094: temporary location and can be reset using tmpreset, $storehash should
                   15095: be a hash reference, returns nothing on success
1.191     harris41 15096: 
                   15097: =item *
                   15098: 
1.243     albertel 15099: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15100: similar to restore, but all data is stored in a temporary location and
                   15101: can be reset using tmpreset. Returns a hash of values on success,
                   15102: error string otherwise.
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15107: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15108: 
                   15109: =item *
                   15110: 
1.243     albertel 15111: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15112: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15113: 
                   15114: =item *
                   15115: 
1.243     albertel 15116: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15117: namesp ($udom and $uname are optional)
1.191     harris41 15118: 
                   15119: =item *
                   15120: 
1.702     albertel 15121: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15122: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15123: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15124: 
1.702     albertel 15125: $range should be either an integer '100' (give me the first 100
                   15126:                                            matching records)
                   15127:               or be  two integers sperated by a - with no spaces
                   15128:                  '30-50' (give me the 30th through the 50th matching
                   15129:                           records)
1.449     matthew  15130: =item *
                   15131: 
                   15132: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15133: $store can be a scalar, an array reference, or if the amount to be 
                   15134: incremented is > 1, a hash reference.
                   15135: 
                   15136: ($udom and $uname are optional)
1.191     harris41 15137: 
                   15138: =item *
                   15139: 
1.243     albertel 15140: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15141: ($udom and $uname are optional)
1.191     harris41 15142: 
                   15143: =item *
                   15144: 
1.243     albertel 15145: cput($namespace,$storehash,$udom,$uname) : critical put
                   15146: ($udom and $uname are optional)
1.191     harris41 15147: 
                   15148: =item *
                   15149: 
1.748     albertel 15150: newput($namespace,$storehash,$udom,$uname) :
                   15151: 
                   15152: Attempts to store the items in the $storehash, but only if they don't
                   15153: currently exist, if this succeeds you can be certain that you have 
                   15154: successfully created a new key value pair in the $namespace db.
                   15155: 
                   15156: 
                   15157: Args:
                   15158:  $namespace: name of database to store values to
                   15159:  $storehash: hashref to store to the db
                   15160:  $udom: (optional) domain of user containing the db
                   15161:  $uname: (optional) name of user caontaining the db
                   15162: 
                   15163: Returns:
                   15164:  'ok' -> succeeded in storing all keys of $storehash
                   15165:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15166:                         least <key> already existed in the db (other
                   15167:                         requested keys may also already exist)
1.967     bisitz   15168:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15169:  'con_lost' -> unable to contact request server
                   15170:  'refused' -> action was not allowed by remote machine
                   15171: 
                   15172: 
                   15173: =item *
                   15174: 
1.243     albertel 15175: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15176: reference filled in from namesp (encrypts the return communication)
                   15177: ($udom and $uname are optional)
1.191     harris41 15178: 
                   15179: =item *
                   15180: 
1.243     albertel 15181: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15182: critical subroutine
                   15183: 
1.806     raeburn  15184: =item *
                   15185: 
1.860     raeburn  15186: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15187: array reference filled in from namespace found in domain level on either
                   15188: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15189: 
                   15190: =item *
                   15191: 
1.860     raeburn  15192: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15193: domain level either on specified domain server ($uhome) or primary domain 
                   15194: server ($udom and $uhome are optional)
1.806     raeburn  15195: 
1.943     raeburn  15196: =item * 
                   15197: 
1.1172.2.35  raeburn  15198: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15199: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15200: the target domain.
                   15201: 
                   15202: May also include additional key => value pairs for the following groups:
                   15203: 
                   15204: =over
                   15205: 
                   15206: =item
                   15207: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15208: 
                   15209: =over
                   15210: 
                   15211: =item defaultquota, authorquota
                   15212: 
                   15213: =back
                   15214: 
                   15215: =item
                   15216: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15217: portfolio for users).
                   15218: 
                   15219: =over
                   15220: 
                   15221: =item
                   15222: aboutme, blog, webdav, portfolio
                   15223: 
                   15224: =back
                   15225: 
                   15226: =item
                   15227: requestcourses: ability to request courses, and how requests are processed.
                   15228: 
                   15229: =over
                   15230: 
                   15231: =item
1.1172.2.37  raeburn  15232: official, unofficial, community, textbook
1.1172.2.35  raeburn  15233: 
                   15234: =back
                   15235: 
                   15236: =item
                   15237: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15238: 
                   15239: =over
                   15240: 
                   15241: =item
1.1172.2.44  raeburn  15242: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15243: 
                   15244: =back
                   15245: 
                   15246: =item
                   15247: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15248: for course's uploaded content.
                   15249: 
                   15250: =over
                   15251: 
                   15252: =item
1.1172.2.68  raeburn  15253: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15254: communityquota, textbookquota
1.1172.2.35  raeburn  15255: 
                   15256: =back
                   15257: 
                   15258: =item
                   15259: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15260: on your servers.
                   15261: 
                   15262: =over
                   15263: 
                   15264: =item
                   15265: remotesessions, hostedsessions
                   15266: 
                   15267: =back
                   15268: 
                   15269: =back
                   15270: 
                   15271: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15272: utility to create a configuration.db file on a domain's primary library server
                   15273: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15274: -- corresponding values are authentication type (internal, krb4, krb5,
                   15275: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15276: will be available. Values are retrieved from cache (if current), unless the
                   15277: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15278: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15279: 
                   15280: Typical usage:
1.943     raeburn  15281: 
1.1172.2.35  raeburn  15282: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15283: 
1.243     albertel 15284: =back
                   15285: 
                   15286: =head2 Network Status Functions
                   15287: 
                   15288: =over 4
1.191     harris41 15289: 
                   15290: =item *
                   15291: 
1.1137    raeburn  15292: dirlist() : return directory list based on URI (first arg).
                   15293: 
                   15294: Inputs: 1 required, 5 optional.
                   15295: 
                   15296: =over
                   15297: 
                   15298: =item 
                   15299: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15300: 
                   15301: =item
                   15302: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15303: 
                   15304: =item
                   15305: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15306: 
                   15307: =item
                   15308: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15309: 
                   15310: =item
                   15311: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15312: 
                   15313: =item 
                   15314: $alternateRoot - path to prepend in place of path from $uri.
                   15315: 
                   15316: =back
                   15317: 
                   15318: Returns: Array of up to two items.
                   15319: 
                   15320: =over
                   15321: 
                   15322: a reference to an array of files/subdirectories
                   15323: 
                   15324: =over
                   15325: 
                   15326: Each element in the array of files/subdirectories is a & separated list of
                   15327: item name and the result of running stat on the item.  If dirlist was requested
                   15328: for a file instead of a directory, the item name will be ''. For a directory 
                   15329: listing, if the item is a metadata file, the element will end &N&M 
                   15330: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15331: default copyright set (1).  
                   15332: 
                   15333: =back
                   15334: 
                   15335: a scalar containing error condition (if encountered).
                   15336: 
                   15337: =over
                   15338: 
                   15339: =item 
                   15340: no_host (no homeserver identified for $username:$domain).
                   15341: 
                   15342: =item 
                   15343: no_such_host (server contacted for listing not identified as valid host).
                   15344: 
                   15345: =item 
                   15346: con_lost (connection to remote server failed).
                   15347: 
                   15348: =item 
                   15349: refused (invalid $username:$domain received on lond side).
                   15350: 
                   15351: =item 
                   15352: no_such_dir (directory at specified path on lond side does not exist). 
                   15353: 
                   15354: =item 
                   15355: empty (directory at specified path on lond side is empty).
                   15356: 
                   15357: =over
                   15358: 
                   15359: This is currently not encountered because the &ls3, &ls2, 
                   15360: &ls (_handler) routines on the lond side do not filter out
                   15361: . and .. from a directory listing. 
                   15362: 
                   15363: =back
                   15364: 
                   15365: =back
                   15366: 
                   15367: =back
1.191     harris41 15368: 
                   15369: =item *
                   15370: 
1.243     albertel 15371: spareserver() : find server with least workload from spare.tab
                   15372: 
1.986     foxr     15373: 
                   15374: =item *
                   15375: 
                   15376: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15377: if there is no corresponding loncapa host.
                   15378: 
1.243     albertel 15379: =back
                   15380: 
1.986     foxr     15381: 
1.243     albertel 15382: =head2 Apache Request
                   15383: 
                   15384: =over 4
1.191     harris41 15385: 
                   15386: =item *
                   15387: 
1.243     albertel 15388: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15389: localhost, posts hash
                   15390: 
                   15391: =back
                   15392: 
                   15393: =head2 Data to String to Data
                   15394: 
                   15395: =over 4
1.191     harris41 15396: 
                   15397: =item *
                   15398: 
1.243     albertel 15399: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15400: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15401: 
                   15402: =item *
                   15403: 
1.243     albertel 15404: hashref2str($hashref) : convert a hashref into a string complete with
                   15405: escaping and '=' and '&' separators, supports elements that are
                   15406: arrayrefs and hashrefs
1.191     harris41 15407: 
                   15408: =item *
                   15409: 
1.243     albertel 15410: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15411: with escaping and '&' separators, supports elements that are arrayrefs
                   15412: and hashrefs
1.191     harris41 15413: 
                   15414: =item *
                   15415: 
1.243     albertel 15416: str2hash($string) : convert string to hash using unescaping and
                   15417: splitting on '=' and '&', supports elements that are arrayrefs and
                   15418: hashrefs
1.191     harris41 15419: 
                   15420: =item *
                   15421: 
1.243     albertel 15422: str2array($string) : convert string to hash using unescaping and
                   15423: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15424: 
                   15425: =back
                   15426: 
                   15427: =head2 Logging Routines
                   15428: 
                   15429: 
                   15430: These routines allow one to make log messages in the lonnet.log and
                   15431: lonnet.perm logfiles.
1.191     harris41 15432: 
1.1119    foxr     15433: =over 4
                   15434: 
1.191     harris41 15435: =item *
                   15436: 
1.243     albertel 15437: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15438: 
                   15439: =item *
                   15440: 
1.243     albertel 15441: logthis() : append message to the normal lonnet.log file, it gets
                   15442: preiodically rolled over and deleted.
1.191     harris41 15443: 
                   15444: =item *
                   15445: 
1.243     albertel 15446: logperm() : append a permanent message to lonnet.perm.log, this log
                   15447: file never gets deleted by any automated portion of the system, only
                   15448: messages of critical importance should go in here.
                   15449: 
1.1119    foxr     15450: 
1.243     albertel 15451: =back
                   15452: 
                   15453: =head2 General File Helper Routines
                   15454: 
                   15455: =over 4
1.191     harris41 15456: 
                   15457: =item *
                   15458: 
1.481     raeburn  15459: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15460: (a) files in /uploaded
                   15461:   (i) If a local copy of the file exists - 
                   15462:       compares modification date of local copy with last-modified date for 
                   15463:       definitive version stored on home server for course. If local copy is 
                   15464:       stale, requests a new version from the home server and stores it. 
                   15465:       If the original has been removed from the home server, then local copy 
                   15466:       is unlinked.
                   15467:   (ii) If local copy does not exist -
                   15468:       requests the file from the home server and stores it. 
                   15469:   
                   15470:   If $caller is 'uploadrep':  
                   15471:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15472:     for request for files originally uploaded via DOCS. 
                   15473:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15474:   
                   15475:   Otherwise:
                   15476:      This indicates a call from the content generation phase of the request.
                   15477:      -  returns the entire contents of the file or -1.
                   15478:      
                   15479: (b) files in /res
                   15480:    - returns the entire contents of a file or -1; 
                   15481:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15482: 
1.712     albertel 15483: 
                   15484: =item *
                   15485: 
                   15486: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15487:                   reference
                   15488: 
                   15489: returns either a stat() list of data about the file or an empty list
                   15490: if the file doesn't exist or couldn't find out about it (connection
                   15491: problems or user unknown)
                   15492: 
1.191     harris41 15493: =item *
                   15494: 
1.243     albertel 15495: filelocation($dir,$file) : returns file system location of a file
                   15496: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15497: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15498: and a file of ../bob will become /a/bob)
1.191     harris41 15499: 
                   15500: =item *
                   15501: 
                   15502: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15503: filelocation except for hrefs
                   15504: 
                   15505: =item *
                   15506: 
1.1172.2.49  raeburn  15507: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15508: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15509: 
1.243     albertel 15510: =back
                   15511: 
1.608     albertel 15512: =head2 Usererfile file routines (/uploaded*)
                   15513: 
                   15514: =over 4
                   15515: 
                   15516: =item *
                   15517: 
                   15518: userfileupload(): main rotine for putting a file in a user or course's
                   15519:                   filespace, arguments are,
                   15520: 
1.620     albertel 15521:  formname - required - this is the name of the element in $env where the
1.608     albertel 15522:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15523:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15524:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15525:  context - if coursedoc, store the file in the course of the active role
                   15526:              of the current user; 
                   15527:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15528:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15529:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15530:          if undefined, it will be placed in "unknown"
                   15531: 
                   15532:  (This routine calls clean_filename() to remove any dangerous
                   15533:  characters from the filename, and then calls finuserfileupload() to
                   15534:  complete the transaction)
                   15535: 
                   15536:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15537:  and /adm/notfound.html if unsuccessful
                   15538: 
                   15539: =item *
                   15540: 
                   15541: clean_filename(): routine for cleaing a filename up for storage in
                   15542:                  userfile space, argument is:
                   15543: 
                   15544:  filename - proposed filename
                   15545: 
                   15546: returns: the new clean filename
                   15547: 
                   15548: =item *
                   15549: 
1.1090    raeburn  15550: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15551: userspace, probably shouldn't be called directly
                   15552: 
                   15553:   docuname: username or courseid of destination for the file
                   15554:   docudom: domain of user/course of destination for the file
                   15555:   formname: same as for userfileupload()
1.1090    raeburn  15556:   fname: filename (including subdirectories) for the file
                   15557:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15558:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15559:   allfiles: reference to hash used to store objects found by parser
                   15560:   codebase: reference to hash used for codebases of java objects found by parser
                   15561:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15562:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15563:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15564:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15565:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15566:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15567:   mimetype: reference to scalar to accommodate mime type determined
                   15568:             from File::MMagic if $parser = parse.
1.608     albertel 15569: 
                   15570:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15571:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15572:  was 'overwrite').
                   15573:  
1.608     albertel 15574: 
                   15575: =item *
                   15576: 
                   15577: renameuserfile(): renames an existing userfile to a new name
                   15578: 
                   15579:   Args:
                   15580:    docuname: username or courseid of destination for the file
                   15581:    docudom: domain of user/course of destination for the file
                   15582:    old: current file name (including any subdirs under userfiles)
                   15583:    new: desired file name (including any subdirs under userfiles)
                   15584: 
                   15585: =item *
                   15586: 
                   15587: mkdiruserfile(): creates a directory is a userfiles dir
                   15588: 
                   15589:   Args:
                   15590:    docuname: username or courseid of destination for the file
                   15591:    docudom: domain of user/course of destination for the file
                   15592:    dir: dir to create (including any subdirs under userfiles)
                   15593: 
                   15594: =item *
                   15595: 
                   15596: removeuserfile(): removes a file that exists in userfiles
                   15597: 
                   15598:   Args:
                   15599:    docuname: username or courseid of destination for the file
                   15600:    docudom: domain of user/course of destination for the file
                   15601:    fname: filname to delete (including any subdirs under userfiles)
                   15602: 
                   15603: =item *
                   15604: 
                   15605: removeuploadedurl(): convience function for removeuserfile()
                   15606: 
                   15607:   Args:
                   15608:    url:  a full /uploaded/... url to delete
                   15609: 
1.747     albertel 15610: =item * 
                   15611: 
                   15612: get_portfile_permissions():
                   15613:   Args:
                   15614:     domain: domain of user or course contain the portfolio files
                   15615:     user: name of user or num of course contain the portfolio files
                   15616:   Returns:
                   15617:     hashref of a dump of the proper file_permissions.db
                   15618:    
                   15619: 
                   15620: =item * 
                   15621: 
                   15622: get_access_controls():
                   15623: 
                   15624: Args:
                   15625:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15626:   group: (optional) the group you want the files associated with
                   15627:   file: (optional) the file you want access info on
                   15628: 
                   15629: Returns:
1.749     raeburn  15630:     a hash (keys are file names) of hashes containing
                   15631:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15632:         values are XML containing access control settings (see below) 
1.747     albertel 15633: 
                   15634: Internal notes:
                   15635: 
1.749     raeburn  15636:  access controls are stored in file_permissions.db as key=value pairs.
                   15637:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15638:         where scope -> public,guest,course,group,domains or users.
                   15639:               end -> UNIX time for end of access (0 -> no end date)
                   15640:               start -> UNIX time for start of access
                   15641: 
                   15642:     value -> XML description of access control
                   15643:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15644:             <start></start>
                   15645:             <end></end>
                   15646: 
                   15647:             <password></password>  for scope type = guest
                   15648: 
                   15649:             <domain></domain>     for scope type = course or group
                   15650:             <number></number>
                   15651:             <roles id="">
                   15652:              <role></role>
                   15653:              <access></access>
                   15654:              <section></section>
                   15655:              <group></group>
                   15656:             </roles>
                   15657: 
                   15658:             <dom></dom>         for scope type = domains
                   15659: 
                   15660:             <users>             for scope type = users
                   15661:              <user>
                   15662:               <uname></uname>
                   15663:               <udom></udom>
                   15664:              </user>
                   15665:             </users>
                   15666:            </scope> 
                   15667:               
                   15668:  Access data is also aggregated for each file in an additional key=value pair:
                   15669:  key -> path to file/file_name\0accesscontrol 
                   15670:  value -> reference to hash
                   15671:           hash contains key = value pairs
                   15672:           where key = uniqueID:scope_end_start
                   15673:                 value = UNIX time record was last updated
                   15674: 
                   15675:           Used to improve speed of look-ups of access controls for each file.  
                   15676:  
                   15677:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15678: 
1.1172.2.13  raeburn  15679: =item *
                   15680: 
1.749     raeburn  15681: modify_access_controls():
                   15682: 
                   15683: Modifies access controls for a portfolio file
                   15684: Args
                   15685: 1. file name
                   15686: 2. reference to hash of required changes,
                   15687: 3. domain
                   15688: 4. username
                   15689:   where domain,username are the domain of the portfolio owner 
                   15690:   (either a user or a course) 
                   15691: 
                   15692: Returns:
                   15693: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15694: 2. result of deletions ('ok' or 'error', with error message).
                   15695: 3. reference to hash of any new or updated access controls.
                   15696: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15697:    key = integer (inbound ID)
1.1172.2.13  raeburn  15698:    value = uniqueID
                   15699: 
                   15700: =item *
                   15701: 
                   15702: get_timebased_id():
                   15703: 
                   15704: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15705: course via the Course Editor (e.g., folders, composite pages,
                   15706: group bulletin boards).
                   15707: 
                   15708: Args: (first three required; six others optional)
                   15709: 
                   15710: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15711:    docssequence, or name of group
                   15712: 
                   15713: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15714:    e.g., num, boardids
                   15715: 
                   15716: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15717:    file will be named nohist_namespace.db
                   15718: 
                   15719: 4. cdom: domain of course; default is current course domain from %env
                   15720: 
                   15721: 5. cnum: course number; default is current course number from %env
                   15722: 
                   15723: 6. idtype: set to concat if an additional digit is to be appended to the
                   15724:    unix timestamp to form the suffix, if the plain timestamp is already
                   15725:    in use.  Default is to not do this, but simply increment the unix
                   15726:    timestamp by 1 until a unique key is obtained.
                   15727: 
                   15728: 7. who: holder of locking key; defaults to user:domain for user.
                   15729: 
                   15730: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15731:    retrying); default is 3.
                   15732: 
                   15733: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15734: 
                   15735: Returns:
                   15736: 
                   15737: 1. suffix obtained (numeric)
                   15738: 
                   15739: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15740: 
                   15741: 3. error: contains (localized) error message if an error occurred.
                   15742: 
1.747     albertel 15743: 
1.608     albertel 15744: =back
                   15745: 
1.243     albertel 15746: =head2 HTTP Helper Routines
                   15747: 
                   15748: =over 4
                   15749: 
1.191     harris41 15750: =item *
                   15751: 
                   15752: escape() : unpack non-word characters into CGI-compatible hex codes
                   15753: 
                   15754: =item *
                   15755: 
                   15756: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15757: 
1.243     albertel 15758: =back
                   15759: 
                   15760: =head1 PRIVATE SUBROUTINES
                   15761: 
                   15762: =head2 Underlying communication routines (Shouldn't call)
                   15763: 
                   15764: =over 4
                   15765: 
                   15766: =item *
                   15767: 
                   15768: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15769: 
                   15770: =item *
                   15771: 
                   15772: reply() : uses subreply to send a message to remote machine, logs all failures
                   15773: 
                   15774: =item *
                   15775: 
                   15776: critical() : passes a critical message to another server; if cannot
                   15777: get through then place message in connection buffer directory and
                   15778: returns con_delayed, if incapable of saving message, returns
                   15779: con_failed
                   15780: 
                   15781: =item *
                   15782: 
                   15783: reconlonc() : tries to reconnect lonc client processes.
                   15784: 
                   15785: =back
                   15786: 
                   15787: =head2 Resource Access Logging
                   15788: 
                   15789: =over 4
                   15790: 
                   15791: =item *
                   15792: 
                   15793: flushcourselogs() : flush (save) buffer logs and access logs
                   15794: 
                   15795: =item *
                   15796: 
                   15797: courselog($what) : save message for course in hash
                   15798: 
                   15799: =item *
                   15800: 
                   15801: courseacclog($what) : save message for course using &courselog().  Perform
                   15802: special processing for specific resource types (problems, exams, quizzes, etc).
                   15803: 
1.191     harris41 15804: =item *
                   15805: 
                   15806: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15807: as a PerlChildExitHandler
1.243     albertel 15808: 
                   15809: =back
                   15810: 
                   15811: =head2 Other
                   15812: 
                   15813: =over 4
                   15814: 
                   15815: =item *
                   15816: 
                   15817: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15818: 
                   15819: =back
                   15820: 
                   15821: =cut
1.877     foxr     15822: 

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