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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.111! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.110 2019/08/19 17:27:49 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
                     81:             %managerstab);
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.1073    raeburn   266:                     my $protocol = $protocol{$lonhost};
                    267:                     $protocol = 'http' if ($protocol ne 'https');
                    268:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    269:                     my $request=new HTTP::Request('GET',$url);
                    270:                     my $response=$ua->request($request);
                    271:                     unless ($response->is_error()) {
                    272:                         my $content = $response->content;
1.1081    raeburn   273:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   274:                             $loncaparev = $1;
                    275:                         }
                    276:                     }
                    277:                 } else {
                    278:                     $loncaparev = $loncaparevs{$lonhost};
                    279:                 }
1.1081    raeburn   280:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   281:                 $loncaparev = $1;
                    282:             }
1.993     raeburn   283:         }
1.1073    raeburn   284:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   285:     }
                    286: }
                    287: 
1.1074    raeburn   288: sub get_server_homeID {
                    289:     my ($hostname,$ignore_cache,$caller) = @_;
                    290:     unless ($ignore_cache) {
                    291:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    292:         if (defined($cached)) {
                    293:             return $serverhomeID;
                    294:         }
                    295:     }
                    296:     my $cachetime = 12*3600;
                    297:     my $serverhomeID;
                    298:     if ($caller eq 'loncron') { 
                    299:         my @machine_ids = &machine_ids($hostname);
                    300:         foreach my $id (@machine_ids) {
                    301:             my $response = &reply('serverhomeID',$id);
                    302:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    303:                 $serverhomeID = $response;
                    304:                 last;
                    305:             }
                    306:         }
                    307:         if ($serverhomeID eq '') {
                    308:             $serverhomeID = $machine_ids[-1];
                    309:         }
                    310:     } else {
                    311:         $serverhomeID = $serverhomeIDs{$hostname};
                    312:     }
                    313:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    314: }
                    315: 
1.1121    raeburn   316: sub get_remote_globals {
                    317:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   318:     my ($result,%returnhash,%whatneeded);
                    319:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   320:         foreach my $what (sort(keys(%{$whathash}))) {
                    321:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   322:             my ($response,$cached);
1.1121    raeburn   323:             unless ($ignore_cache) {
1.1125    raeburn   324:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   325:             }
                    326:             if (defined($cached)) {
1.1125    raeburn   327:                 $returnhash{$what} = $response;
1.1121    raeburn   328:             } else {
1.1125    raeburn   329:                 $whatneeded{$what} = 1;
1.1121    raeburn   330:             }
                    331:         }
1.1125    raeburn   332:         if (keys(%whatneeded) == 0) {
                    333:             $result = 'ok';
                    334:         } else {
1.1121    raeburn   335:             my $requested = &freeze_escape(\%whatneeded);
                    336:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   337:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    338:                 ($rep eq 'unknown_cmd')) {
                    339:                 $result = $rep;
                    340:             } else {
                    341:                 $result = 'ok';
1.1121    raeburn   342:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   343:                 foreach my $item (@pairs) {
                    344:                     my ($key,$value)=split(/=/,$item,2);
                    345:                     my $what = &unescape($key);
                    346:                     my $hashid = $lonhost.'-'.$what;
                    347:                     $returnhash{$what}=&thaw_unescape($value);
                    348:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   349:                 }
                    350:             }
                    351:         }
                    352:     }
1.1125    raeburn   353:     return ($result,\%returnhash);
1.1121    raeburn   354: }
                    355: 
1.1124    raeburn   356: sub remote_devalidate_cache {
1.1172.2.35  raeburn   357:     my ($lonhost,$cachekeys) = @_;
                    358:     my $items;
                    359:     return unless (ref($cachekeys) eq 'ARRAY');
                    360:     my $cachestr = join('&',@{$cachekeys});
                    361:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   362: }
                    363: 
1.1       albertel  364: # -------------------------------------------------- Non-critical communication
                    365: sub subreply {
                    366:     my ($cmd,$server)=@_;
1.838     albertel  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      368:     #
                    369:     #  With loncnew process trimming, there's a timing hole between lonc server
                    370:     #  process exit and the master server picking up the listen on the AF_UNIX
                    371:     #  socket.  In that time interval, a lock file will exist:
                    372: 
                    373:     my $lockfile=$peerfile.".lock";
                    374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   375: 	sleep(0.1);
1.549     foxr      376:     }
                    377:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      378:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      379:     #
1.550     foxr      380:     #   We'll give the connection a few tries before abandoning it.  If
                    381:     #   connection is not possible, we'll con_lost back to the client.
                    382:     #   
                    383:     my $client;
                    384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    386: 				      Type    => SOCK_STREAM,
                    387: 				      Timeout => 10);
1.869     albertel  388: 	if ($client) {
1.550     foxr      389: 	    last;		# Connected!
1.850     albertel  390: 	} else {
1.853     albertel  391: 	    &create_connection(&hostname($server),$server);
1.550     foxr      392: 	}
1.1172.2.79  raeburn   393:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      394:     }
                    395:     my $answer;
                    396:     if ($client) {
1.704     albertel  397: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      398: 	$answer=<$client>;
                    399: 	if (!$answer) { $answer="con_lost"; }
                    400: 	chomp($answer);
                    401:     } else {
                    402: 	$answer = 'con_lost';	# Failed connection.
                    403:     }
1.1       albertel  404:     return $answer;
                    405: }
                    406: 
                    407: sub reply {
                    408:     my ($cmd,$server)=@_;
1.838     albertel  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  410:     my $answer=subreply($cmd,$server);
1.65      www       411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111! raeburn   412:         my $logged = $cmd;
        !           413:         if ($cmd =~ /^encrypt:([^:]+):/) {
        !           414:             my $subcmd = $1;
        !           415:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
        !           416:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
        !           417:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
        !           418:                 (undef,undef,my @rest) = split(/:/,$cmd);
        !           419:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
        !           420:                     splice(@rest,2,1,'Hidden');
        !           421:                 } elsif ($subcmd eq 'passwd') {
        !           422:                     splice(@rest,2,2,('Hidden','Hidden'));
        !           423:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
        !           424:                          ($subcmd eq 'autoexportgrades')) {
        !           425:                     splice(@rest,3,1,'Hidden');
        !           426:                 }
        !           427:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
        !           428:             }
        !           429:         }
        !           430:         &logthis("<font color=\"blue\">WARNING:".
        !           431:                  " $logged to $server returned $answer</font>");
1.12      www       432:     }
1.1       albertel  433:     return $answer;
                    434: }
                    435: 
                    436: # ----------------------------------------------------------- Send USR1 to lonc
                    437: 
                    438: sub reconlonc {
1.891     albertel  439:     my ($lonid) = @_;
                    440:     if ($lonid) {
1.1172.2.72  raeburn   441:         my $hostname = &hostname($lonid);
1.891     albertel  442: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    443: 	if ($hostname && -e $peerfile) {
                    444: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    445: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    446: 					     Type    => SOCK_STREAM,
                    447: 					     Timeout => 10);
                    448: 	    if ($client) {
                    449: 		print $client ("reset_retries\n");
                    450: 		my $answer=<$client>;
                    451: 		#reset just this one.
                    452: 	    }
                    453: 	}
                    454: 	return;
                    455:     }
                    456: 
1.836     www       457:     &logthis("Trying to reconnect lonc");
1.1       albertel  458:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   459:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  460: 	my $loncpid=<$fh>;
                    461:         chomp($loncpid);
                    462:         if (kill 0 => $loncpid) {
                    463: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    464:             kill USR1 => $loncpid;
                    465:             sleep 1;
1.836     www       466:          } else {
1.12      www       467: 	    &logthis(
1.672     albertel  468:                "<font color=\"blue\">WARNING:".
1.12      www       469:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  470:         }
                    471:     } else {
1.836     www       472: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  473:     }
                    474: }
                    475: 
                    476: # ------------------------------------------------------ Critical communication
1.12      www       477: 
1.1       albertel  478: sub critical {
                    479:     my ($cmd,$server)=@_;
1.838     albertel  480:     unless (&hostname($server)) {
1.672     albertel  481:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       482:                " Critical message to unknown server ($server)</font>");
                    483:         return 'no_such_host';
                    484:     }
1.1       albertel  485:     my $answer=reply($cmd,$server);
                    486:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   487: 	&reconlonc($server);
1.589     albertel  488: 	my $answer=reply($cmd,$server);
1.1       albertel  489:         if ($answer eq 'con_lost') {
                    490:             my $now=time;
                    491:             my $middlename=$cmd;
1.5       www       492:             $middlename=substr($middlename,0,16);
1.1       albertel  493:             $middlename=~s/\W//g;
                    494:             my $dfilename=
1.305     www       495:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    496:             $dumpcount++;
1.1       albertel  497:             {
1.448     albertel  498: 		my $dfh;
1.1172.2.96  raeburn   499: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  500: 		    print $dfh "$cmd\n"; 
                    501: 		    close($dfh);
                    502: 		}
1.1       albertel  503:             }
1.1172.2.79  raeburn   504:             sleep 1;
1.1       albertel  505:             my $wcmd='';
                    506:             {
1.448     albertel  507: 		my $dfh;
1.1172.2.96  raeburn   508: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  509: 		    $wcmd=<$dfh>; 
                    510: 		    close($dfh);
                    511: 		}
1.1       albertel  512:             }
                    513:             chomp($wcmd);
1.7       www       514:             if ($wcmd eq $cmd) {
1.672     albertel  515: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       516:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  517:                 &logperm("D:$server:$cmd");
                    518: 	        return 'con_delayed';
                    519:             } else {
1.672     albertel  520:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       521:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  522:                 &logperm("F:$server:$cmd");
                    523:                 return 'con_failed';
                    524:             }
                    525:         }
                    526:     }
                    527:     return $answer;
1.405     albertel  528: }
                    529: 
1.755     albertel  530: # ------------------------------------------- check if return value is an error
                    531: 
                    532: sub error {
                    533:     my ($result) = @_;
1.756     albertel  534:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  535: 	if ($2 == 2) { return undef; }
                    536: 	return $1;
                    537:     }
                    538:     return undef;
                    539: }
                    540: 
1.783     albertel  541: sub convert_and_load_session_env {
                    542:     my ($lonidsdir,$handle)=@_;
                    543:     my @profile;
                    544:     {
1.917     albertel  545: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    546: 	if (!$opened) {
1.915     albertel  547: 	    return 0;
                    548: 	}
1.783     albertel  549: 	flock($idf,LOCK_SH);
                    550: 	@profile=<$idf>;
                    551: 	close($idf);
                    552:     }
                    553:     my %temp_env;
                    554:     foreach my $line (@profile) {
1.786     albertel  555: 	if ($line !~ m/=/) {
                    556: 	    return 0;
                    557: 	}
1.783     albertel  558: 	chomp($line);
                    559: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    560: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    561:     }
                    562:     unlink("$lonidsdir/$handle.id");
                    563:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    564: 	    0640)) {
                    565: 	%disk_env = %temp_env;
                    566: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    567: 	untie(%disk_env);
                    568:     }
1.786     albertel  569:     return 1;
1.783     albertel  570: }
                    571: 
1.374     www       572: # ------------------------------------------- Transfer profile into environment
1.780     albertel  573: my $env_loaded;
                    574: sub transfer_profile_to_env {
1.788     albertel  575:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    576:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       577: 
1.720     albertel  578:     if (!defined($lonidsdir)) {
                    579: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    580:     }
                    581:     if (!defined($handle)) {
                    582:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    583:     }
                    584: 
1.786     albertel  585:     my $convert;
                    586:     {
1.917     albertel  587:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    588: 	if (!$opened) {
1.915     albertel  589: 	    return;
                    590: 	}
1.786     albertel  591: 	flock($idf,LOCK_SH);
                    592: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    593: 		&GDBM_READER(),0640)) {
                    594: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    595: 	    untie(%disk_env);
                    596: 	} else {
                    597: 	    $convert = 1;
                    598: 	}
                    599:     }
                    600:     if ($convert) {
                    601: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    602: 	    &logthis("Failed to load session, or convert session.");
                    603: 	}
1.374     www       604:     }
1.783     albertel  605: 
1.786     albertel  606:     my %remove;
1.783     albertel  607:     while ( my $envname = each(%env) ) {
1.433     matthew   608:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    609:             if ($time < time-300) {
1.783     albertel  610:                 $remove{$key}++;
1.433     matthew   611:             }
                    612:         }
                    613:     }
1.783     albertel  614: 
1.619     albertel  615:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  616:     $env_loaded=1;
1.783     albertel  617:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   618:         &delenv($expired_key);
1.374     www       619:     }
1.1       albertel  620: }
                    621: 
1.916     albertel  622: # ---------------------------------------------------- Check for valid session 
                    623: sub check_for_valid_session {
1.1172.2.96  raeburn   624:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  625:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   626:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   627:     if ($name eq 'lonDAV') {
                    628:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    629:     } else {
                    630:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   631:         if ($name eq '') {
                    632:             $name = 'lonID';
                    633:         }
                    634:     }
                    635:     if ($name eq 'lonID') {
                    636:         $secure = 'lonSID';
                    637:         $linkname = 'lonLinkID';
                    638:         $pubname = 'lonPubID';
                    639:         if (exists($cookies{$secure})) {
                    640:             $lonid=$cookies{$secure};
                    641:         } elsif (exists($cookies{$name})) {
                    642:             $lonid=$cookies{$name};
                    643:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    644:             $lonid=$cookies{$linkname};
                    645:         } elsif (exists($cookies{$pubname})) {
                    646:             $lonid=$cookies{$pubname};
                    647:         }
                    648:     } else {
                    649:         $lonid=$cookies{$name};
                    650:     }
                    651:     return undef if (!$lonid);
                    652: 
                    653:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    654:     if (-l "$lonidsdir/$handle.id") {
                    655:         my $link = readlink("$lonidsdir/$handle.id");
                    656:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    657:             $handle = $1;
                    658:         }
1.1155    raeburn   659:     }
1.1172.2.96  raeburn   660:     if (!-e "$lonidsdir/$handle.id") {
                    661:         if ((ref($domref)) && ($name eq 'lonID') &&
                    662:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    663:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    664:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    665:                 $$domref = $possudom;
                    666:             }
                    667:         }
                    668:         return undef;
                    669:     }
1.916     albertel  670: 
1.917     albertel  671:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    672:     return undef if (!$opened);
1.916     albertel  673: 
                    674:     flock($idf,LOCK_SH);
                    675:     my %disk_env;
                    676:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    677: 	    &GDBM_READER(),0640)) {
                    678: 	return undef;	
                    679:     }
                    680: 
                    681:     if (!defined($disk_env{'user.name'})
                    682: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   683:         untie(%disk_env);
1.916     albertel  684: 	return undef;
                    685:     }
1.1172.2.18  raeburn   686: 
1.1172.2.36  raeburn   687:     if (ref($userhashref) eq 'HASH') {
                    688:         $userhashref->{'name'} = $disk_env{'user.name'};
                    689:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   690:     }
1.1172.2.107  raeburn   691:     untie(%disk_env);
1.1172.2.18  raeburn   692: 
1.916     albertel  693:     return $handle;
                    694: }
                    695: 
1.830     albertel  696: sub timed_flock {
                    697:     my ($file,$lock_type) = @_;
                    698:     my $failed=0;
                    699:     eval {
                    700: 	local $SIG{__DIE__}='DEFAULT';
                    701: 	local $SIG{ALRM}=sub {
                    702: 	    $failed=1;
                    703: 	    die("failed lock");
                    704: 	};
                    705: 	alarm(13);
                    706: 	flock($file,$lock_type);
                    707: 	alarm(0);
                    708:     };
                    709:     if ($failed) {
                    710: 	return undef;
                    711:     } else {
                    712: 	return 1;
                    713:     }
                    714: }
                    715: 
1.1172.2.107  raeburn   716: sub get_sessionfile_vars {
                    717:     my ($handle,$lonidsdir,$storearr) = @_;
                    718:     my %returnhash;
                    719:     unless (ref($storearr) eq 'ARRAY') {
                    720:         return %returnhash;
                    721:     }
                    722:     if (-l "$lonidsdir/$handle.id") {
                    723:         my $link = readlink("$lonidsdir/$handle.id");
                    724:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    725:             $handle = $1;
                    726:         }
                    727:     }
                    728:     if ((-e "$lonidsdir/$handle.id") &&
                    729:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    730:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    731:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    732:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    733:                 flock($idf,LOCK_SH);
                    734:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    735:                         &GDBM_READER(),0640)) {
                    736:                     foreach my $item (@{$storearr}) {
                    737:                         $returnhash{$item} = $disk_env{$item};
                    738:                     }
                    739:                     untie(%disk_env);
                    740:                 }
                    741:             }
                    742:         }
                    743:     }
                    744:     return %returnhash;
                    745: }
                    746: 
1.5       www       747: # ---------------------------------------------------------- Append Environment
                    748: 
                    749: sub appenv {
1.949     raeburn   750:     my ($newenv,$roles) = @_;
                    751:     if (ref($newenv) eq 'HASH') {
                    752:         foreach my $key (keys(%{$newenv})) {
                    753:             my $refused = 0;
                    754: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    755:                 $refused = 1;
                    756:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   757:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   758:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    759:                         $refused = 0;
                    760:                     }
                    761:                 }
                    762:             }
                    763:             if ($refused) {
                    764:                 &logthis("<font color=\"blue\">WARNING: ".
                    765:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    766:                          .'</font>');
                    767: 	        delete($newenv->{$key});
                    768:             } else {
                    769:                 $env{$key}=$newenv->{$key};
                    770:             }
                    771:         }
1.1172.2.96  raeburn   772:         my $lonids = $perlvar{'lonIDsDir'};
                    773:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    774:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    775:             if ($opened
                    776: 	        && &timed_flock($env_file,LOCK_EX)
                    777: 	        &&
                    778: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    779: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    780: 	        while (my ($key,$value) = each(%{$newenv})) {
                    781: 	            $disk_env{$key} = $value;
                    782: 	        }
                    783: 	        untie(%disk_env);
                    784:             }
1.35      www       785:         }
1.191     harris41  786:     }
1.56      www       787:     return 'ok';
                    788: }
                    789: # ----------------------------------------------------- Delete from Environment
                    790: 
                    791: sub delenv {
1.1104    raeburn   792:     my ($delthis,$regexp,$roles) = @_;
                    793:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    794:         my $refused = 1;
                    795:         if (ref($roles) eq 'ARRAY') {
                    796:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    797:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    798:                 $refused = 0;
                    799:             }
                    800:         }
                    801:         if ($refused) {
                    802:             &logthis("<font color=\"blue\">WARNING: ".
                    803:                      "Attempt to delete from environment ".$delthis);
                    804:             return 'error';
                    805:         }
1.56      www       806:     }
1.917     albertel  807:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    808:     if ($opened
1.915     albertel  809: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  810: 	&&
                    811: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    812: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  813: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   814: 	    if ($regexp) {
                    815:                 if ($key=~/^$delthis/) {
                    816:                     delete($env{$key});
                    817:                     delete($disk_env{$key});
                    818:                 } 
                    819:             } else {
                    820:                 if ($key=~/^\Q$delthis\E/) {
                    821: 		    delete($env{$key});
                    822: 		    delete($disk_env{$key});
                    823: 	        }
                    824:             }
1.448     albertel  825: 	}
1.783     albertel  826: 	untie(%disk_env);
1.5       www       827:     }
                    828:     return 'ok';
1.369     albertel  829: }
                    830: 
1.790     albertel  831: sub get_env_multiple {
                    832:     my ($name) = @_;
                    833:     my @values;
                    834:     if (defined($env{$name})) {
                    835:         # exists is it an array
                    836:         if (ref($env{$name})) {
                    837:             @values=@{ $env{$name} };
                    838:         } else {
                    839:             $values[0]=$env{$name};
                    840:         }
                    841:     }
                    842:     return(@values);
                    843: }
                    844: 
1.958     www       845: # ------------------------------------------------------------------- Locking
                    846: 
                    847: sub set_lock {
                    848:     my ($text)=@_;
                    849:     $locknum++;
                    850:     my $id=$$.'-'.$locknum;
                    851:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    852:              'session.lock.'.$id => $text});
                    853:     return $id;
                    854: }
                    855: 
                    856: sub get_locks {
                    857:     my $num=0;
                    858:     my %texts=();
                    859:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    860:        if ($lock=~/\w/) {
                    861:           $num++;
                    862:           $texts{$lock}=$env{'session.lock.'.$lock};
                    863:        }
                    864:    }
                    865:    return ($num,%texts);
                    866: }
                    867: 
                    868: sub remove_lock {
                    869:     my ($id)=@_;
                    870:     my $newlocks='';
                    871:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    872:        if (($lock=~/\w/) && ($lock ne $id)) {
                    873:           $newlocks.=','.$lock;
                    874:        }
                    875:     }
                    876:     &appenv({'session.locks' => $newlocks});
                    877:     &delenv('session.lock.'.$id);
                    878: }
                    879: 
                    880: sub remove_all_locks {
                    881:     my $activelocks=$env{'session.locks'};
                    882:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    883:        if ($lock=~/\w/) {
                    884:           &remove_lock($lock);
                    885:        }
                    886:     }
                    887: }
                    888: 
                    889: 
1.369     albertel  890: # ------------------------------------------ Find out current server userload
                    891: sub userload {
                    892:     my $numusers=0;
                    893:     {
                    894: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    895: 	my $filename;
                    896: 	my $curtime=time;
                    897: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  898: 	    next if ($filename eq '.' || $filename eq '..');
                    899: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  900: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  901: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  902: 	}
                    903: 	closedir(LONIDS);
                    904:     }
                    905:     my $userloadpercent=0;
                    906:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    907:     if ($maxuserload) {
1.371     albertel  908: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  909:     }
1.372     albertel  910:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  911:     return $userloadpercent;
1.283     www       912: }
                    913: 
1.1       albertel  914: # ------------------------------ Find server with least workload from spare.tab
1.11      www       915: 
1.1       albertel  916: sub spareserver {
1.1083    raeburn   917:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  918:     my $spare_server;
1.370     albertel  919:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  920:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    921:                                                      :  $userloadpercent;
1.1083    raeburn   922:     my ($uint_dom,$remotesessions);
                    923:     if (($udom ne '') && (&domain($udom) ne '')) {
                    924:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    925:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    926:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    927:         $remotesessions = $udomdefaults{'remotesessions'};
                    928:     }
1.1123    raeburn   929:     my $spareshash = &this_host_spares($udom);
                    930:     if (ref($spareshash) eq 'HASH') {
                    931:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    932:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   933:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    934:                                              $try_server));
1.1123    raeburn   935: 	        ($spare_server, $lowest_load) =
                    936: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    937:             }
1.1083    raeburn   938:         }
1.784     albertel  939: 
1.1123    raeburn   940:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    941: 
                    942:         if (!$found_server) {
                    943:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    944: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   945:                     next unless (&spare_can_host($udom,$uint_dom,
                    946:                                                  $remotesessions,$try_server));
1.1123    raeburn   947: 	            ($spare_server, $lowest_load) =
                    948: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    949:                 }
                    950: 	    }
                    951:         }
1.784     albertel  952:     }
                    953: 
                    954:     if (!$want_server_name) {
1.968     raeburn   955:         my $protocol = 'http';
                    956:         if ($protocol{$spare_server} eq 'https') {
                    957:             $protocol = $protocol{$spare_server};
                    958:         }
1.1001    raeburn   959:         if (defined($spare_server)) {
                    960:             my $hostname = &hostname($spare_server);
1.1083    raeburn   961:             if (defined($hostname)) {
1.1001    raeburn   962: 	        $spare_server = $protocol.'://'.$hostname;
                    963:             }
                    964:         }
1.784     albertel  965:     }
                    966:     return $spare_server;
                    967: }
                    968: 
                    969: sub compare_server_load {
1.1172.2.41  raeburn   970:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    971: 
                    972:     if ($required) {
                    973:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    974:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    975:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    976:         if (($major eq '' && $minor eq '') ||
                    977:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    978:             return ($spare_server,$lowest_load);
                    979:         }
                    980:     }
1.784     albertel  981: 
                    982:     my $loadans     = &reply('load',    $try_server);
                    983:     my $userloadans = &reply('userload',$try_server);
                    984: 
                    985:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   986: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  987:     }
                    988: 
                    989:     my $load;
                    990:     if ($loadans =~ /\d/) {
                    991: 	if ($userloadans =~ /\d/) {
                    992: 	    #both are numbers, pick the bigger one
                    993: 	    $load = ($loadans > $userloadans) ? $loadans 
                    994: 		                              : $userloadans;
1.411     albertel  995: 	} else {
1.784     albertel  996: 	    $load = $loadans;
1.411     albertel  997: 	}
1.784     albertel  998:     } else {
                    999: 	$load = $userloadans;
                   1000:     }
                   1001: 
                   1002:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1003: 	$spare_server = $try_server;
                   1004: 	$lowest_load  = $load;
1.370     albertel 1005:     }
1.784     albertel 1006:     return ($spare_server,$lowest_load);
1.202     matthew  1007: }
1.914     albertel 1008: 
                   1009: # --------------------------- ask offload servers if user already has a session
                   1010: sub find_existing_session {
                   1011:     my ($udom,$uname) = @_;
1.1123    raeburn  1012:     my $spareshash = &this_host_spares($udom);
                   1013:     if (ref($spareshash) eq 'HASH') {
                   1014:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1015:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1016:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1017:             }
                   1018:         }
                   1019:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1020:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1021:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1022:             }
                   1023:         }
1.914     albertel 1024:     }
                   1025:     return;
                   1026: }
                   1027: 
1.1172.2.107  raeburn  1028: # check if user's browser sent load balancer cookie and server still has session
                   1029: # and is not overloaded.
                   1030: sub check_for_balancer_cookie {
                   1031:     my ($r,$update_mtime) = @_;
                   1032:     my ($otherserver,$cookie);
                   1033:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1034:     if (exists($cookies{'balanceID'})) {
                   1035:         my $balid = $cookies{'balanceID'};
                   1036:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1037:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1038:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1039:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1040:                 my ($possudom,$possuname) = ($1,$2);
                   1041:                 my $has_session = 0;
                   1042:                 if ((&domain($possudom) ne '') &&
                   1043:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1044:                     my $try_server;
                   1045:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1046:                     if ($opened) {
                   1047:                         flock($idf,LOCK_SH);
                   1048:                         while (my $line = <$idf>) {
                   1049:                             chomp($line);
                   1050:                             if (&hostname($line) ne '') {
                   1051:                                 $try_server = $line;
                   1052:                                 last;
                   1053:                             }
                   1054:                         }
                   1055:                         close($idf);
                   1056:                         if (($try_server) &&
                   1057:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1058:                             my $lowest_load = 30000;
                   1059:                             ($otherserver,$lowest_load) =
                   1060:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1061:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1062:                                 $has_session = 1;
                   1063:                             } else {
                   1064:                                 undef($otherserver);
                   1065:                             }
                   1066:                         }
                   1067:                     }
                   1068:                 }
                   1069:                 if ($has_session) {
                   1070:                     if ($update_mtime) {
                   1071:                         my $atime = my $mtime = time;
                   1072:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1073:                     }
                   1074:                 } else {
                   1075:                     unlink("$balancedir/$cookie.id");
                   1076:                 }
                   1077:             }
                   1078:         }
                   1079:     }
                   1080:     return ($otherserver,$cookie);
                   1081: }
                   1082: 
                   1083: sub delbalcookie {
                   1084:     my ($cookie,$balancer) =@_;
                   1085:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1086:         my ($udom,$uname) = ($1,$2);
                   1087:         my $uprimary_id = &domain($udom,'primary');
                   1088:         my $uintdom = &internet_dom($uprimary_id);
                   1089:         my $intdom = &internet_dom($balancer);
                   1090:         my $serverhomedom = &host_domain($balancer);
                   1091:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1092:             return &reply("delbalcookie:$cookie",$balancer);
                   1093:         }
                   1094:     }
                   1095: }
                   1096: 
1.914     albertel 1097: # -------------------------------- ask if server already has a session for user
                   1098: sub has_user_session {
                   1099:     my ($lonid,$udom,$uname) = @_;
                   1100:     my $result = &reply(join(':','userhassession',
                   1101: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1102:     return 1 if ($result eq 'ok');
                   1103: 
                   1104:     return 0;
                   1105: }
                   1106: 
1.1076    raeburn  1107: # --------- determine least loaded server in a user's domain which allows login
                   1108: 
                   1109: sub choose_server {
1.1172.2.47  raeburn  1110:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1111:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1112:     my %servers = &get_servers($udom);
1.1076    raeburn  1113:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1114:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1115:     if ($skiploadbal) {
                   1116:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1117:         unless (defined($cached)) {
                   1118:             my $cachetime = 60*60*24;
                   1119:             my %domconfig =
                   1120:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1121:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1122:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1123:                                            $cachetime);
                   1124:             }
                   1125:         }
                   1126:     }
1.1076    raeburn  1127:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1128:         my $loginvia;
1.1172.2.47  raeburn  1129:         if ($skiploadbal) {
                   1130:             if (ref($balancers) eq 'HASH') {
                   1131:                 next if (exists($balancers->{$lonhost}));
                   1132:             }
                   1133:         }
1.1115    raeburn  1134:         if ($checkloginvia) {
                   1135:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1136:             if ($loginvia) {
                   1137:                 my ($server,$path) = split(/:/,$loginvia);
                   1138:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1139:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1140:                 if ($login_host eq $server) {
                   1141:                     $portal_path = $path;
1.1151    raeburn  1142:                     $isredirect = 1;
1.1116    raeburn  1143:                 }
                   1144:             } else {
                   1145:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1146:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1147:                 if ($login_host eq $lonhost) {
                   1148:                     $portal_path = '';
1.1151    raeburn  1149:                     $isredirect = ''; 
1.1116    raeburn  1150:                 }
                   1151:             }
                   1152:         } else {
1.1076    raeburn  1153:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1154:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1155:         }
                   1156:     }
                   1157:     if ($login_host ne '') {
1.1116    raeburn  1158:         $hostname = &hostname($login_host);
1.1076    raeburn  1159:     }
1.1172.2.88  raeburn  1160:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1161: }
                   1162: 
1.202     matthew  1163: # --------------------------------------------- Try to change a user's password
                   1164: 
                   1165: sub changepass {
1.799     raeburn  1166:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1167:     $currentpass = &escape($currentpass);
                   1168:     $newpass     = &escape($newpass);
1.1030    raeburn  1169:     my $lonhost = $perlvar{'lonHostID'};
                   1170:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1171: 		       $server);
                   1172:     if (! $answer) {
                   1173: 	&logthis("No reply on password change request to $server ".
                   1174: 		 "by $uname in domain $udom.");
                   1175:     } elsif ($answer =~ "^ok") {
                   1176:         &logthis("$uname in $udom successfully changed their password ".
                   1177: 		 "on $server.");
                   1178:     } elsif ($answer =~ "^pwchange_failure") {
                   1179: 	&logthis("$uname in $udom was unable to change their password ".
                   1180: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1181: 		 "or pwchange");
                   1182:     } elsif ($answer =~ "^non_authorized") {
                   1183:         &logthis("$uname in $udom did not get their password correct when ".
                   1184: 		 "attempting to change it on $server.");
                   1185:     } elsif ($answer =~ "^auth_mode_error") {
                   1186:         &logthis("$uname in $udom attempted to change their password despite ".
                   1187: 		 "not being locally or internally authenticated on $server.");
                   1188:     } elsif ($answer =~ "^unknown_user") {
                   1189:         &logthis("$uname in $udom attempted to change their password ".
                   1190: 		 "on $server but were unable to because $server is not ".
                   1191: 		 "their home server.");
                   1192:     } elsif ($answer =~ "^refused") {
                   1193: 	&logthis("$server refused to change $uname in $udom password because ".
                   1194: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1195:     } elsif ($answer =~ "invalid_client") {
                   1196:         &logthis("$server refused to change $uname in $udom password because ".
                   1197:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1198:     }
                   1199:     return $answer;
1.1       albertel 1200: }
                   1201: 
1.169     harris41 1202: # ----------------------- Try to determine user's current authentication scheme
                   1203: 
                   1204: sub queryauthenticate {
                   1205:     my ($uname,$udom)=@_;
1.456     albertel 1206:     my $uhome=&homeserver($uname,$udom);
                   1207:     if (!$uhome) {
                   1208: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1209: 	return 'no_host';
                   1210:     }
                   1211:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1212:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1213: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1214:     }
1.456     albertel 1215:     return $answer;
1.169     harris41 1216: }
                   1217: 
1.1       albertel 1218: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1219: 
1.1       albertel 1220: sub authenticate {
1.1073    raeburn  1221:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1222:     $upass=&escape($upass);
                   1223:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1224:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1225:     my $newhome;
1.836     www      1226:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1227: # Maybe the machine was offline and only re-appeared again recently?
                   1228:         &reconlonc();
                   1229: # One more
1.952     raeburn  1230: 	$uhome=&homeserver($uname,$udom,1);
                   1231:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1232:             if (defined(&domain($udom,'primary'))) {
                   1233:                 $newhome=&domain($udom,'primary');
                   1234:             }
                   1235:             if ($newhome ne '') {
                   1236:                 $uhome = $newhome;
                   1237:             }
                   1238:         }
1.836     www      1239: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1240: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1241: 	    return 'no_host';
                   1242:         }
1.1       albertel 1243:     }
1.1073    raeburn  1244:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1245:     if ($answer eq 'authorized') {
1.952     raeburn  1246:         if ($newhome) {
                   1247:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1248:             return 'no_account_on_host'; 
                   1249:         } else {
                   1250:             &logthis("User $uname at $udom authorized by $uhome");
                   1251:             return $uhome;
                   1252:         }
1.471     albertel 1253:     }
                   1254:     if ($answer eq 'non_authorized') {
                   1255: 	&logthis("User $uname at $udom rejected by $uhome");
                   1256: 	return 'no_host'; 
1.9       www      1257:     }
1.471     albertel 1258:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1259:     return 'no_host';
                   1260: }
                   1261: 
1.1073    raeburn  1262: sub can_host_session {
1.1074    raeburn  1263:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1264:     my $canhost = 1;
1.1074    raeburn  1265:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1266:     if (ref($remotesessions) eq 'HASH') {
                   1267:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1268:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1269:                 $canhost = 0;
                   1270:             } else {
                   1271:                 $canhost = 1;
                   1272:             }
                   1273:         }
                   1274:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1275:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1276:                 $canhost = 1;
                   1277:             } else {
                   1278:                 $canhost = 0;
                   1279:             }
                   1280:         }
                   1281:         if ($canhost) {
                   1282:             if ($remotesessions->{'version'} ne '') {
                   1283:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1284:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1285:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1286:                         my $major = $1;
                   1287:                         my $minor = $2;
                   1288:                         if (($major < $reqmajor ) ||
                   1289:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1290:                             $canhost = 0;
                   1291:                         }
                   1292:                     } else {
                   1293:                         $canhost = 0;
                   1294:                     }
                   1295:                 }
                   1296:             }
                   1297:         }
                   1298:     }
                   1299:     if ($canhost) {
                   1300:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1301:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1302:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1303:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1304:                 if (($uint_dom ne '') && 
                   1305:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1306:                     $canhost = 0;
                   1307:                 } else {
                   1308:                     $canhost = 1;
                   1309:                 }
                   1310:             }
                   1311:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1312:                 if (($uint_dom ne '') && 
                   1313:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1314:                     $canhost = 1;
                   1315:                 } else {
                   1316:                     $canhost = 0;
                   1317:                 }
                   1318:             }
                   1319:         }
                   1320:     }
                   1321:     return $canhost;
                   1322: }
                   1323: 
1.1083    raeburn  1324: sub spare_can_host {
                   1325:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1326:     my $canhost=1;
1.1172.2.62  raeburn  1327:     my $try_server_hostname = &hostname($try_server);
                   1328:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1329:     my $serverhomedom = &host_domain($serverhomeID);
                   1330:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1331:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1332:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1333:             $canhost = 0;
                   1334:         }
                   1335:     }
                   1336:     if (($canhost) && ($uint_dom)) {
                   1337:         my @intdoms;
                   1338:         my $internet_names = &get_internet_names($try_server);
                   1339:         if (ref($internet_names) eq 'ARRAY') {
                   1340:             @intdoms = @{$internet_names};
                   1341:         }
                   1342:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1343:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1344:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1345:                                          $remotesessions,
                   1346:                                          $defdomdefaults{'hostedsessions'});
                   1347:         }
1.1083    raeburn  1348:     }
                   1349:     return $canhost;
                   1350: }
                   1351: 
1.1123    raeburn  1352: sub this_host_spares {
                   1353:     my ($dom) = @_;
1.1126    raeburn  1354:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1355:     my @hosts = &current_machine_ids();
                   1356:     foreach my $lonhost (@hosts) {
                   1357:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1358:             $dom_in_use = $dom;
                   1359:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1360:             last;
                   1361:         }
                   1362:     }
1.1126    raeburn  1363:     if ($dom_in_use ne '') {
                   1364:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1365:     }
                   1366:     if (ref($result) ne 'HASH') {
                   1367:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1368:         $dom_in_use = &host_domain($lonhost_in_use);
                   1369:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1370:         if (ref($result) ne 'HASH') {
                   1371:             $result = \%spareid;
                   1372:         }
                   1373:     }
                   1374:     return $result;
                   1375: }
                   1376: 
                   1377: sub spares_for_offload  {
                   1378:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1379:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1380:     if (defined($cached)) {
                   1381:         return $result;
                   1382:     } else {
1.1126    raeburn  1383:         my $cachetime = 60*60*24;
                   1384:         my %domconfig =
                   1385:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1386:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1387:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1388:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1389:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
1.1126    raeburn  1394:     return;
1.1123    raeburn  1395: }
                   1396: 
1.1129    raeburn  1397: sub get_lonbalancer_config {
                   1398:     my ($servers) = @_;
                   1399:     my ($currbalancer,$currtargets);
                   1400:     if (ref($servers) eq 'HASH') {
                   1401:         foreach my $server (keys(%{$servers})) {
                   1402:             my %what = (
                   1403:                          spareid => 1,
                   1404:                          perlvar => 1,
                   1405:                        );
                   1406:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1407:             if ($result eq 'ok') {
                   1408:                 if (ref($returnhash) eq 'HASH') {
                   1409:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1410:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1411:                             $currbalancer = $server;
                   1412:                             $currtargets = {};
                   1413:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1414:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1415:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1416:                                 }
                   1417:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1418:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1419:                                 }
                   1420:                             }
                   1421:                             last;
                   1422:                         }
                   1423:                     }
                   1424:                 }
                   1425:             }
                   1426:         }
                   1427:     }
                   1428:     return ($currbalancer,$currtargets);
                   1429: }
                   1430: 
                   1431: sub check_loadbalancing {
1.1172.2.88  raeburn  1432:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1433:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1434:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1435:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1436:     my @hosts = &current_machine_ids();
1.1129    raeburn  1437:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1438:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1439:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1440:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1441:     my $domneedscache; 
1.1129    raeburn  1442:     my $cachetime = 60*60*24;
                   1443: 
                   1444:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1445:         $dom_in_use = $udom;
                   1446:         $homeintdom = 1;
                   1447:     } else {
                   1448:         $dom_in_use = $serverhomedom;
                   1449:     }
                   1450:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1451:     unless (defined($cached)) {
                   1452:         my %domconfig =
                   1453:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1454:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1455:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1456:         } else {
                   1457:             $domneedscache = $dom_in_use;
1.1129    raeburn  1458:         }
                   1459:     }
                   1460:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1461:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1462:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1463:         if ($is_balancer) {
                   1464:             if (ref($currrules) eq 'HASH') {
                   1465:                 if ($homeintdom) {
                   1466:                     if ($uname ne '') {
                   1467:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1468:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1469:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1470:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1471:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1472:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1473:                             }
                   1474:                         }
                   1475:                         if ($rule_in_effect eq '') {
                   1476:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1477:                             if ($userenv{'inststatus'} ne '') {
                   1478:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1479:                                 my ($othertitle,$usertypes,$types) =
                   1480:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1481:                                 if (ref($types) eq 'ARRAY') {
                   1482:                                     foreach my $type (@{$types}) {
                   1483:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1484:                                             if (exists($currrules->{$type})) {
                   1485:                                                 $rule_in_effect = $currrules->{$type};
                   1486:                                             }
                   1487:                                         }
                   1488:                                     }
                   1489:                                 }
                   1490:                             } else {
                   1491:                                 if (exists($currrules->{'default'})) {
                   1492:                                     $rule_in_effect = $currrules->{'default'};
                   1493:                                 }
                   1494:                             }
                   1495:                         }
                   1496:                     } else {
                   1497:                         if (exists($currrules->{'default'})) {
                   1498:                             $rule_in_effect = $currrules->{'default'};
                   1499:                         }
                   1500:                     }
                   1501:                 } else {
                   1502:                     if ($currrules->{'_LC_external'} ne '') {
                   1503:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1504:                     }
                   1505:                 }
                   1506:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1507:                                                        $uname,$udom);
                   1508:             }
                   1509:         }
                   1510:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1511:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1512:         unless (defined($cached)) {
                   1513:             my %domconfig =
                   1514:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1515:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1516:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1517:             } else {
                   1518:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1519:             }
                   1520:         }
                   1521:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1522:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1523:                 &check_balancer_result($result,@hosts);
                   1524:             if ($is_balancer) {
1.1129    raeburn  1525:                 if (ref($currrules) eq 'HASH') {
                   1526:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1527:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1528:                     }
                   1529:                 }
                   1530:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1531:                                                        $uname,$udom);
                   1532:             }
                   1533:         } else {
                   1534:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1535:                 $is_balancer = 1;
                   1536:                 $offloadto = &this_host_spares($dom_in_use);
                   1537:             }
1.1172.2.75  raeburn  1538:             unless (defined($cached)) {
                   1539:                 $domneedscache = $serverhomedom;
                   1540:             }
1.1129    raeburn  1541:         }
                   1542:     } else {
                   1543:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1544:             $is_balancer = 1;
                   1545:             $offloadto = &this_host_spares($dom_in_use);
                   1546:         }
1.1172.2.75  raeburn  1547:         unless (defined($cached)) {
                   1548:             $domneedscache = $serverhomedom;
                   1549:         }
                   1550:     }
                   1551:     if ($domneedscache) {
                   1552:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1553:     }
1.1172.2.5  raeburn  1554:     if ($is_balancer) {
                   1555:         my $lowest_load = 30000;
                   1556:         if (ref($offloadto) eq 'HASH') {
                   1557:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1558:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1559:                     ($otherserver,$lowest_load) =
                   1560:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1561:                 }
1.1129    raeburn  1562:             }
1.1172.2.5  raeburn  1563:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1564: 
1.1172.2.5  raeburn  1565:             if (!$found_server) {
                   1566:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1567:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1568:                         ($otherserver,$lowest_load) =
                   1569:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1570:                     }
                   1571:                 }
                   1572:             }
                   1573:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1574:             if (@{$offloadto} == 1) {
                   1575:                 $otherserver = $offloadto->[0];
                   1576:             } elsif (@{$offloadto} > 1) {
                   1577:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1578:                     ($otherserver,$lowest_load) =
                   1579:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1580:                 }
                   1581:             }
                   1582:         }
1.1172.2.88  raeburn  1583:         unless ($caller eq 'login') {
                   1584:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1585:                 $is_balancer = 0;
                   1586:                 if ($uname ne '' && $udom ne '') {
                   1587:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1588:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1589:                                  'user.loadbalcheck.time' => time});
                   1590:                     }
1.1172.2.5  raeburn  1591:                 }
1.1129    raeburn  1592:             }
                   1593:         }
1.1172.2.107  raeburn  1594:         unless ($homeintdom) {
                   1595:             undef($setcookie);
                   1596:         }
1.1129    raeburn  1597:     }
1.1172.2.107  raeburn  1598:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1599: }
                   1600: 
1.1172.2.12  raeburn  1601: sub check_balancer_result {
                   1602:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1603:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1604:     if (ref($result) eq 'HASH') {
                   1605:         if ($result->{'lonhost'} ne '') {
                   1606:             my $currbalancer = $result->{'lonhost'};
                   1607:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1608:                 $is_balancer = 1;
                   1609:                 $currtargets = $result->{'targets'};
                   1610:                 $currrules = $result->{'rules'};
                   1611:             }
                   1612:         } else {
                   1613:             foreach my $key (keys(%{$result})) {
                   1614:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1615:                     (ref($result->{$key}) eq 'HASH')) {
                   1616:                     $is_balancer = 1;
                   1617:                     $currrules = $result->{$key}{'rules'};
                   1618:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1619:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1620:                     last;
                   1621:                 }
                   1622:             }
                   1623:         }
                   1624:     }
1.1172.2.107  raeburn  1625:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1626: }
                   1627: 
1.1129    raeburn  1628: sub get_loadbalancer_targets {
                   1629:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1630:     my $offloadto;
1.1172.2.4  raeburn  1631:     if ($rule_in_effect eq 'none') {
                   1632:         return [$perlvar{'lonHostID'}];
                   1633:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1634:         $offloadto = $currtargets;
                   1635:     } else {
                   1636:         if ($rule_in_effect eq 'homeserver') {
                   1637:             my $homeserver = &homeserver($uname,$udom);
                   1638:             if ($homeserver ne 'no_host') {
                   1639:                 $offloadto = [$homeserver];
                   1640:             }
                   1641:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1642:             my %domconfig =
                   1643:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1644:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1645:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1646:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1647:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1648:                     }
                   1649:                 }
                   1650:             } else {
1.1172.2.7  raeburn  1651:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1652:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1653:                 if (&hostname($remotebalancer) ne '') {
                   1654:                     $offloadto = [$remotebalancer];
                   1655:                 }
                   1656:             }
                   1657:         } elsif (&hostname($rule_in_effect) ne '') {
                   1658:             $offloadto = [$rule_in_effect];
                   1659:         }
                   1660:     }
                   1661:     return $offloadto;
                   1662: }
                   1663: 
1.1127    raeburn  1664: sub internet_dom_servers {
                   1665:     my ($dom) = @_;
                   1666:     my (%uniqservers,%servers);
                   1667:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1668:     my @machinedoms = &machine_domains($primaryserver);
                   1669:     foreach my $mdom (@machinedoms) {
                   1670:         my %currservers = %servers;
                   1671:         my %server = &get_servers($mdom);
                   1672:         %servers = (%currservers,%server);
                   1673:     }
                   1674:     my %by_hostname;
                   1675:     foreach my $id (keys(%servers)) {
                   1676:         push(@{$by_hostname{$servers{$id}}},$id);
                   1677:     }
                   1678:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1679:         if (@{$by_hostname{$hostname}} > 1) {
                   1680:             my $match = 0;
                   1681:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1682:                 if (&host_domain($id) eq $dom) {
                   1683:                     $uniqservers{$id} = $hostname;
                   1684:                     $match = 1;
                   1685:                 }
                   1686:             }
                   1687:             unless ($match) {
                   1688:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1689:             }
                   1690:         } else {
                   1691:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1692:         }
                   1693:     }
                   1694:     return %uniqservers;
                   1695: }
                   1696: 
1.1       albertel 1697: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1698: 
1.599     albertel 1699: my %homecache;
1.1       albertel 1700: sub homeserver {
1.230     stredwic 1701:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1702:     my $index="$uname:$udom";
1.426     albertel 1703: 
1.599     albertel 1704:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1705: 
                   1706:     my %servers = &get_servers($udom,'library');
                   1707:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1708:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1709: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1710: 
                   1711: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1712: 	if ($answer eq 'found') {
                   1713: 	    delete($badServerCache{$tryserver}); 
                   1714: 	    return $homecache{$index}=$tryserver;
                   1715: 	} elsif ($answer eq 'no_host') {
                   1716: 	    $badServerCache{$tryserver}=1;
                   1717: 	}
1.1       albertel 1718:     }    
                   1719:     return 'no_host';
1.70      www      1720: }
                   1721: 
                   1722: # ------------------------------------- Find the usernames behind a list of IDs
                   1723: 
                   1724: sub idget {
                   1725:     my ($udom,@ids)=@_;
                   1726:     my %returnhash=();
                   1727:     
1.841     albertel 1728:     my %servers = &get_servers($udom,'library');
                   1729:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1730: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1731: 	$idlist=~tr/A-Z/a-z/; 
                   1732: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1733: 	my @answer=();
                   1734: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1735: 	    @answer=split(/\&/,$reply);
                   1736: 	}                    ;
                   1737: 	my $i;
                   1738: 	for ($i=0;$i<=$#ids;$i++) {
                   1739: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1740: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1741: 	    } 
                   1742: 	}
                   1743:     } 
1.70      www      1744:     return %returnhash;
                   1745: }
                   1746: 
                   1747: # ------------------------------------- Find the IDs behind a list of usernames
                   1748: 
                   1749: sub idrget {
                   1750:     my ($udom,@unames)=@_;
                   1751:     my %returnhash=();
1.800     albertel 1752:     foreach my $uname (@unames) {
                   1753:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1754:     }
1.70      www      1755:     return %returnhash;
                   1756: }
                   1757: 
                   1758: # ------------------------------- Store away a list of names and associated IDs
                   1759: 
                   1760: sub idput {
                   1761:     my ($udom,%ids)=@_;
                   1762:     my %servers=();
1.800     albertel 1763:     foreach my $uname (keys(%ids)) {
                   1764: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1765:         my $uhom=&homeserver($uname,$udom);
1.70      www      1766:         if ($uhom ne 'no_host') {
1.800     albertel 1767:             my $id=&escape($ids{$uname});
1.70      www      1768:             $id=~tr/A-Z/a-z/;
1.800     albertel 1769:             my $esc_unam=&escape($uname);
1.70      www      1770: 	    if ($servers{$uhom}) {
1.800     albertel 1771: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1772:             } else {
1.800     albertel 1773:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1774:             }
                   1775:         }
1.191     harris41 1776:     }
1.800     albertel 1777:     foreach my $server (keys(%servers)) {
                   1778:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1779:     }
1.344     www      1780: }
                   1781: 
1.1172.2.30  raeburn  1782: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1783: 
                   1784: sub iddel {
                   1785:     my ($udom,$idshashref,$uhome)=@_;
                   1786:     my %result=();
                   1787:     unless (ref($idshashref) eq 'HASH') {
                   1788:         return %result;
                   1789:     }
                   1790:     my %servers=();
                   1791:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1792:         my $uhom;
                   1793:         if ($uhome) {
                   1794:             $uhom = $uhome;
                   1795:         } else {
                   1796:             $uhom=&homeserver($uname,$udom);
                   1797:         }
                   1798:         if ($uhom ne 'no_host') {
                   1799:             if ($servers{$uhom}) {
                   1800:                 $servers{$uhom}.='&'.&escape($id);
                   1801:             } else {
                   1802:                 $servers{$uhom}=&escape($id);
                   1803:             }
                   1804:         }
                   1805:     }
                   1806:     foreach my $server (keys(%servers)) {
                   1807:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1808:     }
                   1809:     return %result;
                   1810: }
                   1811: 
1.1023    raeburn  1812: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1813: sub dump_dom {
1.1165    droeschl 1814:     my ($namespace, $udom, $regexp) = @_;
                   1815: 
                   1816:     $udom ||= $env{'user.domain'};
                   1817: 
                   1818:     return () unless $udom;
                   1819: 
                   1820:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1821: }
                   1822: 
1.1023    raeburn  1823: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1824: 
                   1825: sub get_dom {
1.860     raeburn  1826:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1827:     return if ($udom eq 'public');
1.806     raeburn  1828:     my $items='';
                   1829:     foreach my $item (@$storearr) {
                   1830:         $items.=&escape($item).'&';
                   1831:     }
                   1832:     $items=~s/\&$//;
1.860     raeburn  1833:     if (!$udom) {
                   1834:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1835:         return if ($udom eq 'public');
1.860     raeburn  1836:         if (defined(&domain($udom,'primary'))) {
                   1837:             $uhome=&domain($udom,'primary');
                   1838:         } else {
1.874     albertel 1839:             undef($uhome);
1.860     raeburn  1840:         }
                   1841:     } else {
                   1842:         if (!$uhome) {
                   1843:             if (defined(&domain($udom,'primary'))) {
                   1844:                 $uhome=&domain($udom,'primary');
                   1845:             }
                   1846:         }
                   1847:     }
                   1848:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1849:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1850:         my %returnhash;
1.875     albertel 1851:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1852:             return %returnhash;
                   1853:         }
1.806     raeburn  1854:         my @pairs=split(/\&/,$rep);
                   1855:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1856:             return @pairs;
                   1857:         }
                   1858:         my $i=0;
                   1859:         foreach my $item (@$storearr) {
                   1860:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1861:             $i++;
                   1862:         }
                   1863:         return %returnhash;
                   1864:     } else {
1.880     banghart 1865:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1866:     }
                   1867: }
                   1868: 
                   1869: # -------------------------------------------- put items in domain db files 
                   1870: 
                   1871: sub put_dom {
1.860     raeburn  1872:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1873:     if (!$udom) {
                   1874:         $udom=$env{'user.domain'};
                   1875:         if (defined(&domain($udom,'primary'))) {
                   1876:             $uhome=&domain($udom,'primary');
                   1877:         } else {
1.874     albertel 1878:             undef($uhome);
1.860     raeburn  1879:         }
                   1880:     } else {
                   1881:         if (!$uhome) {
                   1882:             if (defined(&domain($udom,'primary'))) {
                   1883:                 $uhome=&domain($udom,'primary');
                   1884:             }
                   1885:         }
                   1886:     } 
                   1887:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1888:         my $items='';
                   1889:         foreach my $item (keys(%$storehash)) {
                   1890:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1891:         }
                   1892:         $items=~s/\&$//;
                   1893:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1894:     } else {
1.860     raeburn  1895:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1896:     }
                   1897: }
                   1898: 
1.1023    raeburn  1899: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1900: sub newput_dom {
1.1023    raeburn  1901:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1902:     my $result;
                   1903:     if (!$udom) {
                   1904:         $udom=$env{'user.domain'};
                   1905:     }
1.1023    raeburn  1906:     if ($udom) {
                   1907:         my $uname = &get_domainconfiguser($udom);
                   1908:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1909:     }
                   1910:     return $result;
                   1911: }
                   1912: 
1.1023    raeburn  1913: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1914: sub del_dom {
1.1023    raeburn  1915:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1916:     if (ref($storearr) eq 'ARRAY') {
                   1917:         if (!$udom) {
                   1918:             $udom=$env{'user.domain'};
                   1919:         }
1.1023    raeburn  1920:         if ($udom) {
                   1921:             my $uname = &get_domainconfiguser($udom); 
                   1922:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1923:         }
                   1924:     }
                   1925: }
                   1926: 
1.1023    raeburn  1927: # ----------------------------------construct domainconfig user for a domain 
                   1928: sub get_domainconfiguser {
                   1929:     my ($udom) = @_;
                   1930:     return $udom.'-domainconfig';
                   1931: }
                   1932: 
1.837     raeburn  1933: sub retrieve_inst_usertypes {
                   1934:     my ($udom) = @_;
                   1935:     my (%returnhash,@order);
1.989     raeburn  1936:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1937:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1938:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1939:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1940:     } else {
                   1941:         if (defined(&domain($udom,'primary'))) {
                   1942:             my $uhome=&domain($udom,'primary');
                   1943:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1944:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1945:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1946:                 return (\%returnhash,\@order);
                   1947:             }
                   1948:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1949:             my @pairs=split(/\&/,$hashitems);
                   1950:             foreach my $item (@pairs) {
                   1951:                 my ($key,$value)=split(/=/,$item,2);
                   1952:                 $key = &unescape($key);
                   1953:                 next if ($key =~ /^error: 2 /);
                   1954:                 $returnhash{$key}=&thaw_unescape($value);
                   1955:             }
                   1956:             my @esc_order = split(/\&/,$orderitems);
                   1957:             foreach my $item (@esc_order) {
                   1958:                 push(@order,&unescape($item));
                   1959:             }
                   1960:         } else {
1.1172.2.44  raeburn  1961:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1962:         }
1.1172.2.44  raeburn  1963:         return (\%returnhash,\@order);
1.837     raeburn  1964:     }
                   1965: }
                   1966: 
1.868     raeburn  1967: sub is_domainimage {
                   1968:     my ($url) = @_;
1.1172.2.74  raeburn  1969:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1970:         if (&domain($1) ne '') {
                   1971:             return '1';
                   1972:         }
                   1973:     }
                   1974:     return;
                   1975: }
                   1976: 
1.899     raeburn  1977: sub inst_directory_query {
                   1978:     my ($srch) = @_;
                   1979:     my $udom = $srch->{'srchdomain'};
                   1980:     my %results;
                   1981:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1982:     my $outcome;
1.899     raeburn  1983:     if ($homeserver ne '') {
1.904     albertel 1984: 	my $queryid=&reply("querysend:instdirsearch:".
                   1985: 			   &escape($srch->{'srchby'}).':'.
                   1986: 			   &escape($srch->{'srchterm'}).':'.
                   1987: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1988: 	my $host=&hostname($homeserver);
                   1989: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  1990: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 1991: 	    return;
                   1992: 	}
                   1993: 	my $response = &get_query_reply($queryid);
                   1994: 	my $maxtries = 5;
                   1995: 	my $tries = 1;
                   1996: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1997: 	    $response = &get_query_reply($queryid);
                   1998: 	    $tries ++;
                   1999: 	}
                   2000: 
                   2001:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2002:             if ($response eq 'unavailable') {
                   2003:                 $outcome = $response;
                   2004:             } else {
                   2005:                 $outcome = 'ok';
                   2006:                 my @matches = split(/\n/,$response);
                   2007:                 foreach my $match (@matches) {
                   2008:                     my ($key,$value) = split(/=/,$match);
                   2009:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2010:                 }
1.899     raeburn  2011:             }
                   2012:         }
                   2013:     }
1.909     raeburn  2014:     return ($outcome,%results);
1.899     raeburn  2015: }
                   2016: 
                   2017: sub usersearch {
                   2018:     my ($srch) = @_;
                   2019:     my $dom = $srch->{'srchdomain'};
                   2020:     my %results;
                   2021:     my %libserv = &all_library();
                   2022:     my $query = 'usersearch';
                   2023:     foreach my $tryserver (keys(%libserv)) {
                   2024:         if (&host_domain($tryserver) eq $dom) {
                   2025:             my $host=&hostname($tryserver);
                   2026:             my $queryid=
1.911     raeburn  2027:                 &reply("querysend:".&escape($query).':'.
                   2028:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2029:                        &escape($srch->{'srchtype'}).':'.
                   2030:                        &escape($srch->{'srchterm'}),$tryserver);
                   2031:             if ($queryid !~/^\Q$host\E\_/) {
                   2032:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2033:                 next;
1.899     raeburn  2034:             }
                   2035:             my $reply = &get_query_reply($queryid);
                   2036:             my $maxtries = 1;
                   2037:             my $tries = 1;
                   2038:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2039:                 $reply = &get_query_reply($queryid);
                   2040:                 $tries ++;
                   2041:             }
                   2042:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2043:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2044:             } else {
1.911     raeburn  2045:                 my @matches;
                   2046:                 if ($reply =~ /\n/) {
                   2047:                     @matches = split(/\n/,$reply);
                   2048:                 } else {
                   2049:                     @matches = split(/\&/,$reply);
                   2050:                 }
1.899     raeburn  2051:                 foreach my $match (@matches) {
                   2052:                     my ($uname,$udom,%userhash);
1.911     raeburn  2053:                     foreach my $entry (split(/:/,$match)) {
                   2054:                         my ($key,$value) =
                   2055:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2056:                         $userhash{$key} = $value;
                   2057:                         if ($key eq 'username') {
                   2058:                             $uname = $value;
                   2059:                         } elsif ($key eq 'domain') {
                   2060:                             $udom = $value;
1.911     raeburn  2061:                         }
1.899     raeburn  2062:                     }
                   2063:                     $results{$uname.':'.$udom} = \%userhash;
                   2064:                 }
                   2065:             }
                   2066:         }
                   2067:     }
                   2068:     return %results;
                   2069: }
                   2070: 
1.912     raeburn  2071: sub get_instuser {
                   2072:     my ($udom,$uname,$id) = @_;
                   2073:     my $homeserver = &domain($udom,'primary');
                   2074:     my ($outcome,%results);
                   2075:     if ($homeserver ne '') {
                   2076:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2077:                            &escape($id).':'.&escape($udom),$homeserver);
                   2078:         my $host=&hostname($homeserver);
                   2079:         if ($queryid !~/^\Q$host\E\_/) {
                   2080:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2081:             return;
                   2082:         }
                   2083:         my $response = &get_query_reply($queryid);
                   2084:         my $maxtries = 5;
                   2085:         my $tries = 1;
                   2086:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2087:             $response = &get_query_reply($queryid);
                   2088:             $tries ++;
                   2089:         }
                   2090:         if (!&error($response) && $response ne 'refused') {
                   2091:             if ($response eq 'unavailable') {
                   2092:                 $outcome = $response;
                   2093:             } else {
                   2094:                 $outcome = 'ok';
                   2095:                 my @matches = split(/\n/,$response);
                   2096:                 foreach my $match (@matches) {
                   2097:                     my ($key,$value) = split(/=/,$match);
                   2098:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2099:                 }
                   2100:             }
                   2101:         }
                   2102:     }
                   2103:     my %userinfo;
                   2104:     if (ref($results{$uname}) eq 'HASH') {
                   2105:         %userinfo = %{$results{$uname}};
                   2106:     } 
                   2107:     return ($outcome,%userinfo);
                   2108: }
                   2109: 
1.1172.2.69  raeburn  2110: sub get_multiple_instusers {
                   2111:     my ($udom,$users,$caller) = @_;
                   2112:     my ($outcome,$results);
                   2113:     if (ref($users) eq 'HASH') {
                   2114:         my $count = keys(%{$users});
                   2115:         my $requested = &freeze_escape($users);
                   2116:         my $homeserver = &domain($udom,'primary');
                   2117:         if ($homeserver ne '') {
                   2118:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2119:             my $host=&hostname($homeserver);
                   2120:             if ($queryid !~/^\Q$host\E\_/) {
                   2121:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2122:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2123:                 return ($outcome,$results);
                   2124:             }
                   2125:             my $response = &get_query_reply($queryid);
                   2126:             my $maxtries = 5;
                   2127:             if ($count > 100) {
                   2128:                 $maxtries = 1+int($count/20);
                   2129:             }
                   2130:             my $tries = 1;
                   2131:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2132:                 $response = &get_query_reply($queryid);
                   2133:                 $tries ++;
                   2134:             }
                   2135:             if ($response eq '') {
                   2136:                 $results = {};
                   2137:                 foreach my $key (keys(%{$users})) {
                   2138:                     my ($uname,$id);
                   2139:                     if ($caller eq 'id') {
                   2140:                         $id = $key;
                   2141:                     } else {
                   2142:                         $uname = $key;
                   2143:                     }
                   2144:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2145:                     $outcome = $resp;
                   2146:                     if ($resp eq 'ok') {
                   2147:                         %{$results} = (%{$results}, %info);
                   2148:                     } else {
                   2149:                         last;
                   2150:                     }
                   2151:                 }
                   2152:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2153:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2154:                     $outcome = $response;
                   2155:                 } else {
                   2156:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2157:                     if ($outcome eq 'ok') {
                   2158:                         $results = &thaw_unescape($userdata);
                   2159:                     }
                   2160:                 }
                   2161:             }
                   2162:         }
                   2163:     }
                   2164:     return ($outcome,$results);
                   2165: }
                   2166: 
1.912     raeburn  2167: sub inst_rulecheck {
1.923     raeburn  2168:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2169:     my %returnhash;
                   2170:     if ($udom ne '') {
                   2171:         if (ref($rules) eq 'ARRAY') {
                   2172:             @{$rules} = map {&escape($_);} (@{$rules});
                   2173:             my $rulestr = join(':',@{$rules});
                   2174:             my $homeserver=&domain($udom,'primary');
                   2175:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2176:                 my $response;
                   2177:                 if ($item eq 'username') {                
                   2178:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2179:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2180:                                               $homeserver));
1.923     raeburn  2181:                 } elsif ($item eq 'id') {
                   2182:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2183:                                               ':'.&escape($id).':'.$rulestr,
                   2184:                                               $homeserver));
1.945     raeburn  2185:                 } elsif ($item eq 'selfcreate') {
                   2186:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2187:                                                &escape($udom).':'.&escape($uname).
                   2188:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2189:                 }
1.912     raeburn  2190:                 if ($response ne 'refused') {
                   2191:                     my @pairs=split(/\&/,$response);
                   2192:                     foreach my $item (@pairs) {
                   2193:                         my ($key,$value)=split(/=/,$item,2);
                   2194:                         $key = &unescape($key);
                   2195:                         next if ($key =~ /^error: 2 /);
                   2196:                         $returnhash{$key}=&thaw_unescape($value);
                   2197:                     }
                   2198:                 }
                   2199:             }
                   2200:         }
                   2201:     }
                   2202:     return %returnhash;
                   2203: }
                   2204: 
                   2205: sub inst_userrules {
1.923     raeburn  2206:     my ($udom,$check) = @_;
1.912     raeburn  2207:     my (%ruleshash,@ruleorder);
                   2208:     if ($udom ne '') {
                   2209:         my $homeserver=&domain($udom,'primary');
                   2210:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2211:             my $response;
                   2212:             if ($check eq 'id') {
                   2213:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2214:                                  $homeserver);
1.943     raeburn  2215:             } elsif ($check eq 'email') {
                   2216:                 $response=&reply('instemailrules:'.&escape($udom),
                   2217:                                  $homeserver);
1.923     raeburn  2218:             } else {
                   2219:                 $response=&reply('instuserrules:'.&escape($udom),
                   2220:                                  $homeserver);
                   2221:             }
1.912     raeburn  2222:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2223:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2224:                 ($response ne 'no_such_host')) {
                   2225:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2226:                 my @pairs=split(/\&/,$hashitems);
                   2227:                 foreach my $item (@pairs) {
                   2228:                     my ($key,$value)=split(/=/,$item,2);
                   2229:                     $key = &unescape($key);
                   2230:                     next if ($key =~ /^error: 2 /);
                   2231:                     $ruleshash{$key}=&thaw_unescape($value);
                   2232:                 }
                   2233:                 my @esc_order = split(/\&/,$orderitems);
                   2234:                 foreach my $item (@esc_order) {
                   2235:                     push(@ruleorder,&unescape($item));
                   2236:                 }
                   2237:             }
                   2238:         }
                   2239:     }
                   2240:     return (\%ruleshash,\@ruleorder);
                   2241: }
                   2242: 
1.976     raeburn  2243: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2244: 
                   2245: sub get_domain_defaults {
1.1172.2.35  raeburn  2246:     my ($domain,$ignore_cache) = @_;
                   2247:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2248:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2249:     unless ($ignore_cache) {
                   2250:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2251:         if (defined($cached)) {
                   2252:             if (ref($result) eq 'HASH') {
                   2253:                 return %{$result};
                   2254:             }
1.943     raeburn  2255:         }
                   2256:     }
                   2257:     my %domdefaults;
                   2258:     my %domconfig =
1.989     raeburn  2259:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2260:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2261:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2262:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2263:                                   'coursecategories','autoenroll',
                   2264:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2265:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2266:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2267:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2268:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2269:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2270:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2271:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2272:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2273:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2274:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2275:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2276:     } else {
                   2277:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2278:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2279:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2280:     }
1.976     raeburn  2281:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2282:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2283:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2284:         } else {
                   2285:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2286:         }
1.1172.2.6  raeburn  2287:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2288:         foreach my $item (@usertools) {
                   2289:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2290:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2291:             }
                   2292:         }
1.1172.2.29  raeburn  2293:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2294:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2295:         }
1.976     raeburn  2296:     }
1.985     raeburn  2297:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2298:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2299:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2300:         }
                   2301:     }
1.1172.2.9  raeburn  2302:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2303:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2304:     }
1.989     raeburn  2305:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2306:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2307:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2308:         }
                   2309:     }
1.1047    raeburn  2310:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2311:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2312:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2313:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2314:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2315:         }
1.1172.2.41  raeburn  2316:         foreach my $type (@coursetypes) {
                   2317:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2318:                 unless ($type eq 'community') {
                   2319:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2320:                 }
                   2321:             }
                   2322:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2323:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2324:             }
1.1172.2.60  raeburn  2325:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2326:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2327:                     $domdefaults{$type.'postsubtimeout'} =
                   2328:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2329:                 }
                   2330:             }
1.1172.2.30  raeburn  2331:         }
1.1172.2.67  raeburn  2332:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2333:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2334:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2335:                 if (@clonecodes) {
                   2336:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2337:                 }
                   2338:             }
                   2339:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2340:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2341:         }
1.1172.2.103  raeburn  2342:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2343:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2344:         }
1.1047    raeburn  2345:     }
1.1073    raeburn  2346:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2347:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2348:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2349:         }
                   2350:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2351:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2352:         }
1.1172.2.62  raeburn  2353:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2354:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2355:         }
1.1073    raeburn  2356:     }
1.1172.2.41  raeburn  2357:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2358:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2359:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2360:                             'approval','limit');
                   2361:             foreach my $type (@coursetypes) {
                   2362:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2363:                     my @mgrdc = ();
                   2364:                     foreach my $item (@settings) {
                   2365:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2366:                             push(@mgrdc,$item);
                   2367:                         }
                   2368:                     }
                   2369:                     if (@mgrdc) {
                   2370:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2371:                     }
                   2372:                 }
                   2373:             }
                   2374:         }
                   2375:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2376:             foreach my $type (@coursetypes) {
                   2377:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2378:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2379:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2380:                     }
                   2381:                 }
                   2382:             }
                   2383:         }
                   2384:     }
1.1172.2.46  raeburn  2385:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2386:         $domdefaults{'catauth'} = 'std';
                   2387:         $domdefaults{'catunauth'} = 'std';
                   2388:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2389:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2390:         }
                   2391:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2392:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2393:         }
                   2394:     }
1.1172.2.76  raeburn  2395:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2396:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2397:     }
1.1172.2.89  raeburn  2398:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2399:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2400:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2401:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2402:         }
                   2403:     }
1.1172.2.23  raeburn  2404:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2405:     return %domdefaults;
                   2406: }
                   2407: 
1.1172.2.106  raeburn  2408: sub get_dom_cats {
                   2409:     my ($dom) = @_;
                   2410:     return unless (&domain($dom));
                   2411:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2412:     unless (defined($cached)) {
                   2413:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2414:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2415:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2416:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2417:             } else {
                   2418:                 $cats = {};
                   2419:             }
                   2420:         } else {
                   2421:             $cats = {};
                   2422:         }
                   2423:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2424:     }
                   2425:     return $cats;
                   2426: }
                   2427: 
                   2428: sub get_dom_instcats {
                   2429:     my ($dom) = @_;
                   2430:     return unless (&domain($dom));
                   2431:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2432:     unless (defined($cached)) {
                   2433:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2434:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2435:         if ($totcodes > 0) {
                   2436:             my $caller = 'global';
                   2437:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2438:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2439:                 $instcats = {
                   2440:                                 codes => \%codes,
                   2441:                                 codetitles => \@codetitles,
                   2442:                                 cat_titles => \%cat_titles,
                   2443:                                 cat_order => \%cat_order,
                   2444:                             };
                   2445:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2446:             }
                   2447:         }
                   2448:     }
                   2449:     return $instcats;
                   2450: }
                   2451: 
                   2452: sub retrieve_instcodes {
                   2453:     my ($coursecodes,$dom) = @_;
                   2454:     my $totcodes;
                   2455:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2456:     foreach my $course (keys(%courses)) {
                   2457:         if (ref($courses{$course}) eq 'HASH') {
                   2458:             if ($courses{$course}{'inst_code'} ne '') {
                   2459:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2460:                 $totcodes ++;
                   2461:             }
                   2462:         }
                   2463:     }
                   2464:     return $totcodes;
                   2465: }
                   2466: 
1.344     www      2467: # --------------------------------------------------- Assign a key to a student
                   2468: 
                   2469: sub assign_access_key {
1.364     www      2470: #
                   2471: # a valid key looks like uname:udom#comments
                   2472: # comments are being appended
                   2473: #
1.498     www      2474:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2475:     $kdom=
1.620     albertel 2476:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2477:     $knum=
1.620     albertel 2478:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2479:     $cdom=
1.620     albertel 2480:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2481:     $cnum=
1.620     albertel 2482:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2483:     $udom=$env{'user.name'} unless (defined($udom));
                   2484:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2485:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2486:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2487:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2488:                                                   # assigned to this person
                   2489:                                                   # - this should not happen,
1.345     www      2490:                                                   # unless something went wrong
                   2491:                                                   # the first time around
                   2492: # ready to assign
1.364     www      2493:         $logentry=$1.'; '.$logentry;
1.496     www      2494:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2495:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2496: # key now belongs to user
1.346     www      2497: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2498:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2499:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2500:                 return 'ok';
                   2501:             } else {
                   2502:                 return 
                   2503:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2504: 	    }
                   2505:         } else {
                   2506:             return 'error: Could not assign key, try again later.';
                   2507:         }
1.364     www      2508:     } elsif (!$existing{$ckey}) {
1.345     www      2509: # the key does not exist
                   2510: 	return 'error: The key does not exist';
                   2511:     } else {
                   2512: # the key is somebody else's
                   2513: 	return 'error: The key is already in use';
                   2514:     }
1.344     www      2515: }
                   2516: 
1.364     www      2517: # ------------------------------------------ put an additional comment on a key
                   2518: 
                   2519: sub comment_access_key {
                   2520: #
                   2521: # a valid key looks like uname:udom#comments
                   2522: # comments are being appended
                   2523: #
                   2524:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2525:     $cdom=
1.620     albertel 2526:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2527:     $cnum=
1.620     albertel 2528:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2529:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2530:     if ($existing{$ckey}) {
                   2531:         $existing{$ckey}.='; '.$logentry;
                   2532: # ready to assign
1.367     www      2533:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2534:                                                  $cdom,$cnum) eq 'ok') {
                   2535: 	    return 'ok';
                   2536:         } else {
                   2537: 	    return 'error: Count not store comment.';
                   2538:         }
                   2539:     } else {
                   2540: # the key does not exist
                   2541: 	return 'error: The key does not exist';
                   2542:     }
                   2543: }
                   2544: 
1.344     www      2545: # ------------------------------------------------------ Generate a set of keys
                   2546: 
                   2547: sub generate_access_keys {
1.364     www      2548:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2549:     $cdom=
1.620     albertel 2550:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2551:     $cnum=
1.620     albertel 2552:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2553:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2554:     unless (($cdom) && ($cnum)) { return 0; }
                   2555:     if ($number>10000) { return 0; }
                   2556:     sleep(2); # make sure don't get same seed twice
                   2557:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2558:     my $total=0;
                   2559:     for (my $i=1;$i<=$number;$i++) {
                   2560:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2561:                   sprintf("%lx",int(100000*rand)).'-'.
                   2562:                   sprintf("%lx",int(100000*rand));
                   2563:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2564:        $newkey=~s/0/h/g; # and also 0 and O
                   2565:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2566:        if ($existing{$newkey}) {
                   2567:            $i--;
                   2568:        } else {
1.364     www      2569: 	  if (&put('accesskeys',
                   2570:               { $newkey => '# generated '.localtime().
1.620     albertel 2571:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2572:                            '; '.$logentry },
                   2573: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2574:               $total++;
                   2575: 	  }
                   2576:        }
                   2577:     }
1.620     albertel 2578:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2579:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2580:     return $total;
                   2581: }
                   2582: 
                   2583: # ------------------------------------------------------- Validate an accesskey
                   2584: 
                   2585: sub validate_access_key {
                   2586:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2587:     $cdom=
1.620     albertel 2588:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2589:     $cnum=
1.620     albertel 2590:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2591:     $udom=$env{'user.domain'} unless (defined($udom));
                   2592:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2593:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2594:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2595: }
                   2596: 
                   2597: # ------------------------------------- Find the section of student in a course
1.652     albertel 2598: sub devalidate_getsection_cache {
                   2599:     my ($udom,$unam,$courseid)=@_;
                   2600:     my $hashid="$udom:$unam:$courseid";
                   2601:     &devalidate_cache_new('getsection',$hashid);
                   2602: }
1.298     matthew  2603: 
1.815     albertel 2604: sub courseid_to_courseurl {
                   2605:     my ($courseid) = @_;
                   2606:     #already url style courseid
                   2607:     return $courseid if ($courseid =~ m{^/});
                   2608: 
                   2609:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2610: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2611: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2612: 	return "/$cdom/$cnum";
                   2613:     }
                   2614: 
                   2615:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2616:     if (exists($courseinfo{'num'})) {
                   2617: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2618:     }
                   2619: 
                   2620:     return undef;
                   2621: }
                   2622: 
1.298     matthew  2623: sub getsection {
                   2624:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2625:     my $cachetime=1800;
1.551     albertel 2626: 
                   2627:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2628:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2629:     if (defined($cached)) { return $result; }
                   2630: 
1.298     matthew  2631:     my %Pending; 
                   2632:     my %Expired;
                   2633:     #
                   2634:     # Each role can either have not started yet (pending), be active, 
                   2635:     #    or have expired.
                   2636:     #
                   2637:     # If there is an active role, we are done.
                   2638:     #
                   2639:     # If there is more than one role which has not started yet, 
                   2640:     #     choose the one which will start sooner
                   2641:     # If there is one role which has not started yet, return it.
                   2642:     #
                   2643:     # If there is more than one expired role, choose the one which ended last.
                   2644:     # If there is a role which has expired, return it.
                   2645:     #
1.815     albertel 2646:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2647:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2648:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2649:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2650:         my $section=$1;
                   2651:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2652:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2653:         my $now=time;
1.548     albertel 2654:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2655:             $Expired{$end}=$section;
                   2656:             next;
                   2657:         }
1.548     albertel 2658:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2659:             $Pending{$start}=$section;
                   2660:             next;
                   2661:         }
1.599     albertel 2662:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2663:     }
                   2664:     #
                   2665:     # Presumedly there will be few matching roles from the above
                   2666:     # loop and the sorting time will be negligible.
                   2667:     if (scalar(keys(%Pending))) {
                   2668:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2669:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2670:     } 
                   2671:     if (scalar(keys(%Expired))) {
                   2672:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2673:         my $time = pop(@sorted);
1.599     albertel 2674:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2675:     }
1.599     albertel 2676:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2677: }
1.70      www      2678: 
1.599     albertel 2679: sub save_cache {
                   2680:     &purge_remembered();
1.722     albertel 2681:     #&Apache::loncommon::validate_page();
1.620     albertel 2682:     undef(%env);
1.780     albertel 2683:     undef($env_loaded);
1.599     albertel 2684: }
1.452     albertel 2685: 
1.599     albertel 2686: my $to_remember=-1;
                   2687: my %remembered;
                   2688: my %accessed;
                   2689: my $kicks=0;
                   2690: my $hits=0;
1.849     albertel 2691: sub make_key {
                   2692:     my ($name,$id) = @_;
1.872     albertel 2693:     if (length($id) > 65 
                   2694: 	&& length(&escape($id)) > 200) {
                   2695: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2696:     }
1.849     albertel 2697:     return &escape($name.':'.$id);
                   2698: }
                   2699: 
1.599     albertel 2700: sub devalidate_cache_new {
                   2701:     my ($name,$id,$debug) = @_;
                   2702:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2703:     my $remembered_id=$name.':'.$id;
1.849     albertel 2704:     $id=&make_key($name,$id);
1.599     albertel 2705:     $memcache->delete($id);
1.1172.2.81  raeburn  2706:     delete($remembered{$remembered_id});
                   2707:     delete($accessed{$remembered_id});
1.599     albertel 2708: }
                   2709: 
                   2710: sub is_cached_new {
                   2711:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2712:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2713:                                      # keys in %remembered hash, which persists for
                   2714:                                      # duration of request (no restriction on key length).
                   2715:     if (exists($remembered{$remembered_id})) {
                   2716: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2717: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2718: 	$hits++;
1.1172.2.81  raeburn  2719: 	return ($remembered{$remembered_id},1);
1.599     albertel 2720:     }
1.1172.2.81  raeburn  2721:     $id=&make_key($name,$id);
1.599     albertel 2722:     my $value = $memcache->get($id);
                   2723:     if (!(defined($value))) {
                   2724: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2725: 	return (undef,undef);
1.416     albertel 2726:     }
1.599     albertel 2727:     if ($value eq '__undef__') {
                   2728: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2729: 	$value=undef;
                   2730:     }
1.1172.2.81  raeburn  2731:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2732:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2733:     return ($value,1);
                   2734: }
                   2735: 
                   2736: sub do_cache_new {
                   2737:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2738:     my $remembered_id=$name.':'.$id;
1.849     albertel 2739:     $id=&make_key($name,$id);
1.599     albertel 2740:     my $setvalue=$value;
                   2741:     if (!defined($setvalue)) {
                   2742: 	$setvalue='__undef__';
                   2743:     }
1.623     albertel 2744:     if (!defined($time) ) {
                   2745: 	$time=600;
                   2746:     }
1.599     albertel 2747:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2748:     my $result = $memcache->set($id,$setvalue,$time);
                   2749:     if (! $result) {
1.872     albertel 2750: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2751: 	$memcache->disconnect_all();
1.872     albertel 2752:     }
1.600     albertel 2753:     # need to make a copy of $value
1.1172.2.81  raeburn  2754:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2755:     return $value;
                   2756: }
                   2757: 
                   2758: sub make_room {
1.1172.2.81  raeburn  2759:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2760: 
1.1172.2.81  raeburn  2761:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2762:                                     : $value;
1.599     albertel 2763:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2764:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2765:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2766:     my $to_kick;
                   2767:     my $max_time=0;
                   2768:     foreach my $other (keys(%accessed)) {
                   2769: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2770: 	    $to_kick=$other;
                   2771: 	    $max_time=&tv_interval($accessed{$other});
                   2772: 	}
                   2773:     }
                   2774:     delete($remembered{$to_kick});
                   2775:     delete($accessed{$to_kick});
                   2776:     $kicks++;
                   2777:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2778:     return;
                   2779: }
                   2780: 
1.599     albertel 2781: sub purge_remembered {
1.604     albertel 2782:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2783:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2784:     undef(%remembered);
                   2785:     undef(%accessed);
1.428     albertel 2786: }
1.70      www      2787: # ------------------------------------- Read an entry from a user's environment
                   2788: 
                   2789: sub userenvironment {
                   2790:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2791:     my $items;
                   2792:     foreach my $item (@what) {
                   2793:         $items.=&escape($item).'&';
                   2794:     }
                   2795:     $items=~s/\&$//;
1.70      www      2796:     my %returnhash=();
1.1009    raeburn  2797:     my $uhome = &homeserver($unam,$udom);
                   2798:     unless ($uhome eq 'no_host') {
                   2799:         my @answer=split(/\&/, 
                   2800:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2801:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2802:             return %returnhash;
                   2803:         }
1.1009    raeburn  2804:         my $i;
                   2805:         for ($i=0;$i<=$#what;$i++) {
                   2806: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2807:         }
1.70      www      2808:     }
                   2809:     return %returnhash;
1.1       albertel 2810: }
                   2811: 
1.617     albertel 2812: # ---------------------------------------------------------- Get a studentphoto
                   2813: sub studentphoto {
                   2814:     my ($udom,$unam,$ext) = @_;
                   2815:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2816:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2817:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2818:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2819:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2820:             } else {
                   2821:                 my ($result,$perm_reqd)=
1.707     albertel 2822: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2823:                 if ($result eq 'ok') {
                   2824:                     if (!($perm_reqd eq 'yes')) {
                   2825:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2826:                     }
                   2827:                 }
                   2828:             }
                   2829:         }
                   2830:     } else {
                   2831:         my ($result,$perm_reqd) = 
1.707     albertel 2832: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2833:         if ($result eq 'ok') {
                   2834:             if (!($perm_reqd eq 'yes')) {
                   2835:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2836:             }
                   2837:         }
                   2838:     }
                   2839:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2840: }
                   2841: 
                   2842: sub retrievestudentphoto {
                   2843:     my ($udom,$unam,$ext,$type) = @_;
                   2844:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2845:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2846:     if ($ret eq 'ok') {
                   2847:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2848:         if ($type eq 'thumbnail') {
                   2849:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2850:         }
                   2851:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2852:         return $tokenurl;
                   2853:     } else {
                   2854:         if ($type eq 'thumbnail') {
                   2855:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2856:         } else { 
                   2857:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2858:         }
1.617     albertel 2859:     }
                   2860: }
                   2861: 
1.263     www      2862: # -------------------------------------------------------------------- New chat
                   2863: 
                   2864: sub chatsend {
1.724     raeburn  2865:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2866:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2867:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2868:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2869:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2870: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2871: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2872: }
                   2873: 
                   2874: # ------------------------------------------ Find current version of a resource
                   2875: 
                   2876: sub getversion {
                   2877:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2878:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2879:     return &currentversion(&filelocation('',$fname));
                   2880: }
                   2881: 
                   2882: sub currentversion {
                   2883:     my $fname=shift;
                   2884:     my $author=$fname;
                   2885:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2886:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2887:     my $home=&homeserver($uname,$udom);
1.292     www      2888:     if ($home eq 'no_host') { 
                   2889:         return -1; 
                   2890:     }
1.1112    www      2891:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2892:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2893: 	return -1;
                   2894:     }
1.1112    www      2895:     return $answer;
1.263     www      2896: }
                   2897: 
1.1111    www      2898: #
                   2899: # Return special version number of resource if set by override, empty otherwise
                   2900: #
                   2901: sub usedversion {
                   2902:     my $fname=shift;
                   2903:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2904:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2905:     if ($urlversion) { return $urlversion; }
                   2906:     return '';
                   2907: }
                   2908: 
1.1       albertel 2909: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2910: 
1.1       albertel 2911: sub subscribe {
                   2912:     my $fname=shift;
1.761     raeburn  2913:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2914:     $fname=~s/[\n\r]//g;
1.1       albertel 2915:     my $author=$fname;
                   2916:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2917:     my ($udom,$uname)=split(/\//,$author);
                   2918:     my $home=homeserver($uname,$udom);
1.335     albertel 2919:     if ($home eq 'no_host') {
                   2920:         return 'not_found';
1.1       albertel 2921:     }
                   2922:     my $answer=reply("sub:$fname",$home);
1.64      www      2923:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2924: 	$answer.=' by '.$home;
                   2925:     }
1.1       albertel 2926:     return $answer;
                   2927: }
                   2928:     
1.8       www      2929: # -------------------------------------------------------------- Replicate file
                   2930: 
                   2931: sub repcopy {
                   2932:     my $filename=shift;
1.23      www      2933:     $filename=~s/\/+/\//g;
1.1142    raeburn  2934:     my $londocroot = $perlvar{'lonDocRoot'};
                   2935:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2936:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2937:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2938: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2939: 	return &repcopy_userfile($filename);
                   2940:     }
1.532     albertel 2941:     $filename=~s/[\n\r]//g;
1.8       www      2942:     my $transname="$filename.in.transfer";
1.828     www      2943: # FIXME: this should flock
1.607     raeburn  2944:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2945:     my $remoteurl=subscribe($filename);
1.64      www      2946:     if ($remoteurl =~ /^con_lost by/) {
                   2947: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2948:            return 'unavailable';
1.8       www      2949:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2950: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2951: 	   return 'not_found';
1.64      www      2952:     } elsif ($remoteurl =~ /^rejected by/) {
                   2953: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2954:            return 'forbidden';
1.20      www      2955:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2956:            return 'ok';
1.8       www      2957:     } else {
1.290     www      2958:         my $author=$filename;
                   2959:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2960:         my ($udom,$uname)=split(/\//,$author);
                   2961:         my $home=homeserver($uname,$udom);
                   2962:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2963:            my @parts=split(/\//,$filename);
                   2964:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2965:            if ($path ne "$londocroot/res") {
1.8       www      2966:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2967: 	       return 'bad_request';
1.8       www      2968:            }
                   2969:            my $count;
                   2970:            for ($count=5;$count<$#parts;$count++) {
                   2971:                $path.="/$parts[$count]";
                   2972:                if ((-e $path)!=1) {
                   2973: 		   mkdir($path,0777);
                   2974:                }
                   2975:            }
                   2976:            my $ua=new LWP::UserAgent;
                   2977:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2978:            my $response=$ua->request($request,$transname);
                   2979:            if ($response->is_error()) {
                   2980: 	       unlink($transname);
                   2981:                my $message=$response->status_line;
1.672     albertel 2982:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2983:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2984:                return 'unavailable';
1.8       www      2985:            } else {
1.16      www      2986: 	       if ($remoteurl!~/\.meta$/) {
                   2987:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2988:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2989:                   if ($mresponse->is_error()) {
                   2990: 		      unlink($filename.'.meta');
                   2991:                       &logthis(
1.672     albertel 2992:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2993:                   }
                   2994: 	       }
1.8       www      2995:                rename($transname,$filename);
1.607     raeburn  2996:                return 'ok';
1.8       www      2997:            }
1.290     www      2998:        }
1.8       www      2999:     }
1.330     www      3000: }
                   3001: 
                   3002: # ------------------------------------------------ Get server side include body
                   3003: sub ssi_body {
1.381     albertel 3004:     my ($filelink,%form)=@_;
1.606     matthew  3005:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3006:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3007:     }
1.953     www      3008:     my $output='';
                   3009:     my $response;
1.980     raeburn  3010:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3011:        ($output,$response)=&externalssi($filelink);
1.953     www      3012:     } else {
1.1004    droeschl 3013:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3014:        $filelink .= 'inhibitmenu=yes';
1.953     www      3015:        ($output,$response)=&ssi($filelink,%form);
                   3016:     }
1.778     albertel 3017:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3018:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3019:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3020:     if (wantarray) {
                   3021:         return ($output, $response);
                   3022:     } else {
                   3023:         return $output;
                   3024:     }
1.8       www      3025: }
                   3026: 
1.15      www      3027: # --------------------------------------------------------- Server Side Include
                   3028: 
1.782     albertel 3029: sub absolute_url {
                   3030:     my ($host_name) = @_;
                   3031:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3032:     if ($host_name eq '') {
                   3033: 	$host_name = $ENV{'SERVER_NAME'};
                   3034:     }
                   3035:     return $protocol.$host_name;
                   3036: }
                   3037: 
1.942     foxr     3038: #
                   3039: #   Server side include.
                   3040: # Parameters:
                   3041: #  fn     Possibly encrypted resource name/id.
                   3042: #  form   Hash that describes how the rendering should be done
                   3043: #         and other things.
1.944     foxr     3044: # Returns:
1.950     raeburn  3045: #   Scalar context: The content of the response.
                   3046: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3047: #     
1.15      www      3048: sub ssi {
                   3049: 
1.944     foxr     3050:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3051:     my ($request,$response);
1.711     albertel 3052: 
                   3053:     $form{'no_update_last_known'}=1;
1.895     albertel 3054:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3055:     if (%form) {
1.782     albertel 3056:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3057:       $request->content(join('&',map {
                   3058:             my $name = escape($_);
                   3059:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3060:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3061:             : &escape($form{$_}) );
                   3062:         } keys(%form)));
1.23      www      3063:     } else {
1.782     albertel 3064:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3065:     }
                   3066: 
1.15      www      3067:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3068: 
1.1172.2.101  raeburn  3069:     if (($env{'request.course.id'}) &&
                   3070:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3071:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3072:         ($form{'grade_symb'} ne '') &&
                   3073:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3074:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3075:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3076:             my $ua=new LWP::UserAgent;
                   3077:             $ua->local_address('127.0.0.1');
                   3078:             $response = $ua->request($request);
                   3079:         } else {
                   3080:             {
                   3081:                 require LWP::Protocol::http;
                   3082:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3083:                 my $ua=new LWP::UserAgent;
                   3084:                 $response = $ua->request($request);
                   3085:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3086:             }
                   3087:         }
                   3088:     } else {
                   3089:         my $ua=new LWP::UserAgent;
                   3090:         $response = $ua->request($request);
                   3091:     }
1.944     foxr     3092:     if (wantarray) {
1.1172.2.3  raeburn  3093: 	return ($response->content, $response);
1.944     foxr     3094:     } else {
1.1172.2.3  raeburn  3095: 	return $response->content;
1.942     foxr     3096:     }
1.324     www      3097: }
                   3098: 
                   3099: sub externalssi {
                   3100:     my ($url)=@_;
                   3101:     my $ua=new LWP::UserAgent;
                   3102:     my $request=new HTTP::Request('GET',$url);
                   3103:     my $response=$ua->request($request);
1.954     raeburn  3104:     if (wantarray) {
                   3105:         return ($response->content, $response);
                   3106:     } else {
                   3107:         return $response->content;
                   3108:     }
1.15      www      3109: }
1.254     www      3110: 
1.1172.2.98  raeburn  3111: # If the local copy of a replicated resource is outdated, trigger a
                   3112: # connection from the homeserver to flush the delayed queue. If no update
                   3113: # happens, remove local copies of outdated resource (and corresponding
                   3114: # metadata file).
                   3115: 
                   3116: sub remove_stale_resfile {
                   3117:     my ($url) = @_;
                   3118:     my $removed;
                   3119:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3120:         my $audom = $1;
                   3121:         my $auname = $2;
                   3122:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3123:             my $homeserver = &homeserver($auname,$audom);
                   3124:             unless (($homeserver eq 'no_host') ||
                   3125:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3126:                 my $fname = &filelocation('',$url);
                   3127:                 if (-e $fname) {
                   3128:                     my $ua=new LWP::UserAgent;
                   3129:                     $ua->timeout(5);
                   3130:                     my $protocol = $protocol{$homeserver};
                   3131:                     $protocol = 'http' if ($protocol ne 'https');
                   3132:                     my $hostname = &hostname($homeserver);
                   3133:                     if ($hostname) {
                   3134:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
                   3135:                         my $request=new HTTP::Request('HEAD',$uri);
                   3136:                         my $response=$ua->request($request);
                   3137:                         if ($response->is_success()) {
                   3138:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3139:                             my $locmodtime = (stat($fname))[9];
                   3140:                             if ($locmodtime < $remmodtime) {
                   3141:                                 my $stale;
                   3142:                                 my $answer = &reply('pong',$homeserver);
                   3143:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3144:                                     sleep(0.2);
                   3145:                                     $locmodtime = (stat($fname))[9];
                   3146:                                     if ($locmodtime < $remmodtime) {
                   3147:                                         my $posstransfer = $fname.'.in.transfer';
                   3148:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3149:                                             $removed = 1;
                   3150:                                         } else {
                   3151:                                             $stale = 1;
                   3152:                                         }
                   3153:                                     } else {
                   3154:                                         $removed = 1;
                   3155:                                     }
                   3156:                                 } else {
                   3157:                                     $stale = 1;
                   3158:                                 }
                   3159:                                 if ($stale) {
                   3160:                                     unlink($fname);
                   3161:                                     if ($uri!~/\.meta$/) {
                   3162:                                         unlink($fname.'.meta');
                   3163:                                     }
                   3164:                                     &reply("unsub:$fname",$homeserver);
                   3165:                                     $removed = 1;
                   3166:                                 }
                   3167:                             }
                   3168:                         }
                   3169:                     }
                   3170:                 }
                   3171:             }
                   3172:         }
                   3173:     }
                   3174:     return $removed;
                   3175: }
                   3176: 
1.492     albertel 3177: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3178: 
                   3179: sub allowuploaded {
                   3180:     my ($srcurl,$url)=@_;
                   3181:     $url=&clutter(&declutter($url));
                   3182:     my $dir=$url;
                   3183:     $dir=~s/\/[^\/]+$//;
                   3184:     my %httpref=();
                   3185:     my $httpurl=&hreflocation('',$url);
                   3186:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3187:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3188: }
1.477     raeburn  3189: 
1.1172.2.13  raeburn  3190: #
                   3191: # Determine if the current user should be able to edit a particular resource,
                   3192: # when viewing in course context.
                   3193: # (a) When viewing resource used to determine if "Edit" item is included in
                   3194: #     Functions.
                   3195: # (b) When displaying folder contents in course editor, used to determine if
                   3196: #     "Edit" link will be displayed alongside resource.
                   3197: #
                   3198: #  input: six args -- filename (decluttered), course number, course domain,
                   3199: #                   url, symb (if registered) and group (if this is a group
                   3200: #                   item -- e.g., bulletin board, group page etc.).
                   3201: #  output: array of five scalars --
                   3202: #          $cfile -- url for file editing if editable on current server
                   3203: #          $home -- homeserver of resource (i.e., for author if published,
                   3204: #                                           or course if uploaded.).
                   3205: #          $switchserver --  1 if server switch will be needed.
                   3206: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3207: #          $forceview -- 1 if icon/link should be to go to view mode
                   3208: #
                   3209: 
                   3210: sub can_edit_resource {
                   3211:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3212:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3213: #
                   3214: # For aboutme pages user can only edit his/her own.
                   3215: #
                   3216:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3217:         my ($sdom,$sname) = ($1,$2);
                   3218:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3219:             $home = $env{'user.home'};
                   3220:             $cfile = $resurl;
                   3221:             if ($env{'form.forceedit'}) {
                   3222:                 $forceview = 1;
                   3223:             } else {
                   3224:                 $forceedit = 1;
                   3225:             }
                   3226:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3227:         } else {
                   3228:             return;
                   3229:         }
                   3230:     }
                   3231: 
                   3232:     if ($env{'request.course.id'}) {
                   3233:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3234:         if ($group ne '') {
                   3235: # if this is a group homepage or group bulletin board, check group privs
                   3236:             my $allowed = 0;
                   3237:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3238:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3239:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3240:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3241:                     $allowed = 1;
                   3242:                 }
                   3243:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3244:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3245:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3246:                     $allowed = 1;
                   3247:                 }
                   3248:             }
                   3249:             if ($allowed) {
                   3250:                 $home=&homeserver($cnum,$cdom);
                   3251:                 if ($env{'form.forceedit'}) {
                   3252:                     $forceview = 1;
                   3253:                 } else {
                   3254:                     $forceedit = 1;
                   3255:                 }
                   3256:                 $cfile = $resurl;
                   3257:             } else {
                   3258:                 return;
                   3259:             }
                   3260:         } else {
1.1172.2.15  raeburn  3261:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3262:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3263:                     return;
                   3264:                 }
                   3265:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3266: #
                   3267: # No edit allowed where CC has switched to student role.
                   3268: #
                   3269:                 return;
                   3270:             }
                   3271:         }
                   3272:     }
                   3273: 
                   3274:     if ($file ne '') {
                   3275:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3276:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3277:                 $uploaded = 1;
                   3278:                 $incourse = 1;
                   3279:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3280:                     $cfile = &hreflocation('',$file);
                   3281:                     if ($env{'form.forceedit'}) {
                   3282:                         $forceview = 1;
                   3283:                     } else {
                   3284:                         $forceedit = 1;
                   3285:                     }
                   3286:                 }
                   3287:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3288:                 $incourse = 1;
                   3289:                 if ($env{'form.forceedit'}) {
                   3290:                     $forceview = 1;
                   3291:                 } else {
                   3292:                     $forceedit = 1;
                   3293:                 }
                   3294:                 $cfile = $resurl;
                   3295:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3296:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3297:                     $incourse = 1;
                   3298:                     if ($env{'form.forceedit'}) {
                   3299:                         $forceview = 1;
                   3300:                     } else {
                   3301:                         $forceedit = 1;
                   3302:                     }
                   3303:                     $cfile = $resurl;
                   3304:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3305:                     $incourse = 1;
                   3306:                     $cfile = $resurl.'/smpedit';
                   3307:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3308:                     $incourse = 1;
                   3309:                     if ($env{'form.forceedit'}) {
                   3310:                         $forceview = 1;
                   3311:                     } else {
                   3312:                         $forceedit = 1;
                   3313:                     }
                   3314:                     $cfile = $resurl;
1.1172.2.15  raeburn  3315:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3316:                     $incourse = 1;
                   3317:                     if ($env{'form.forceedit'}) {
                   3318:                         $forceview = 1;
                   3319:                     } else {
                   3320:                         $forceedit = 1;
                   3321:                     }
                   3322:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3323:                 }
                   3324:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3325:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3326:                 if (&is_on_map($template)) {
                   3327:                     $incourse = 1;
                   3328:                     $forceview = 1;
                   3329:                     $cfile = $template;
                   3330:                 }
                   3331:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3332:                     $incourse = 1;
                   3333:                     if ($env{'form.forceedit'}) {
                   3334:                         $forceview = 1;
                   3335:                     } else {
                   3336:                         $forceedit = 1;
                   3337:                     }
                   3338:                     $cfile = $resurl;
                   3339:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3340:                 $incourse = 1;
                   3341:                 $forceview = 1;
                   3342:                 if ($symb) {
                   3343:                     my ($map,$id,$res)=&decode_symb($symb);
                   3344:                     $env{'request.symb'} = $symb;
                   3345:                     $cfile = &clutter($res);
                   3346:                 } else {
                   3347:                     $cfile = $env{'form.suppurl'};
                   3348:                     $cfile =~ s{^http://}{};
                   3349:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3350:                 }
1.1172.2.31  raeburn  3351:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3352:                 if ($env{'form.forceedit'}) {
                   3353:                     $forceview = 1;
                   3354:                 } else {
                   3355:                     $forceedit = 1;
                   3356:                 }
                   3357:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3358:             }
                   3359:         }
                   3360:         if ($uploaded || $incourse) {
                   3361:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3362:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3363:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3364:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3365:             # Check that the user has permission to edit this resource
                   3366:             my $setpriv = 1;
                   3367:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3368:             if (defined($cfudom)) {
                   3369:                 $home=&homeserver($cfuname,$cfudom);
                   3370:                 $cfile=$file;
                   3371:             }
                   3372:         }
                   3373:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3374:             (($home ne '') && ($home ne 'no_host'))) {
                   3375:             my @ids=&current_machine_ids();
                   3376:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3377:                 $switchserver=1;
                   3378:             }
                   3379:         }
                   3380:     }
                   3381:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3382: }
                   3383: 
                   3384: sub is_course_upload {
                   3385:     my ($file,$cnum,$cdom) = @_;
                   3386:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3387:     $uploadpath =~ s{^\/}{};
                   3388:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3389:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3390:         return 1;
                   3391:     }
                   3392:     return;
                   3393: }
                   3394: 
                   3395: sub in_course {
                   3396:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3397:     if ($hideprivileged) {
                   3398:         my $skipuser;
1.1172.2.23  raeburn  3399:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3400:         my @possdoms = ($cdom);
                   3401:         if ($coursehash{'checkforpriv'}) {
                   3402:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3403:         }
                   3404:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3405:             $skipuser = 1;
                   3406:             if ($coursehash{'nothideprivileged'}) {
                   3407:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3408:                     my $user;
                   3409:                     if ($item =~ /:/) {
                   3410:                         $user = $item;
                   3411:                     } else {
                   3412:                         $user = join(':',split(/[\@]/,$item));
                   3413:                     }
                   3414:                     if ($user eq $uname.':'.$udom) {
                   3415:                         undef($skipuser);
                   3416:                         last;
                   3417:                     }
                   3418:                 }
                   3419:             }
                   3420:             if ($skipuser) {
                   3421:                 return 0;
                   3422:             }
                   3423:         }
                   3424:     }
                   3425:     $type ||= 'any';
                   3426:     if (!defined($cdom) || !defined($cnum)) {
                   3427:         my $cid  = $env{'request.course.id'};
                   3428:         $cdom = $env{'course.'.$cid.'.domain'};
                   3429:         $cnum = $env{'course.'.$cid.'.num'};
                   3430:     }
                   3431:     my $typesref;
                   3432:     if (($type eq 'any') || ($type eq 'all')) {
                   3433:         $typesref = ['active','previous','future'];
                   3434:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3435:         $typesref = [$type];
                   3436:     }
                   3437:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3438:                               $typesref,undef,[$cdom]);
                   3439:     my ($tmp) = keys(%roles);
                   3440:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3441:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3442:     if (@course_roles > 0) {
                   3443:         return 1;
                   3444:     }
                   3445:     return 0;
                   3446: }
                   3447: 
1.478     albertel 3448: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3449: # input: action, courseID, current domain, intended
1.637     raeburn  3450: #        path to file, source of file, instruction to parse file for objects,
                   3451: #        ref to hash for embedded objects,
                   3452: #        ref to hash for codebase of java objects.
1.1095    raeburn  3453: #        reference to scalar to accommodate mime type determined
                   3454: #          from File::MMagic if $parser = parse.
1.637     raeburn  3455: #
1.485     raeburn  3456: # output: url to file (if action was uploaddoc), 
                   3457: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3458: #
1.478     albertel 3459: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3460: # course.
1.477     raeburn  3461: #
1.478     albertel 3462: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3463: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3464: #          course's home server.
1.477     raeburn  3465: #
1.478     albertel 3466: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3467: #          be copied from $source (current location) to 
                   3468: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3469: #         and will then be copied to
                   3470: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3471: #         course's home server.
1.485     raeburn  3472: #
1.481     raeburn  3473: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3474: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3475: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3476: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3477: #         in course's home server.
1.637     raeburn  3478: #
1.477     raeburn  3479: 
                   3480: sub process_coursefile {
1.1095    raeburn  3481:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3482:         $mimetype)=@_;
1.477     raeburn  3483:     my $fetchresult;
1.638     albertel 3484:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3485:     if ($action eq 'propagate') {
1.638     albertel 3486:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3487: 			     $home);
1.481     raeburn  3488:     } else {
1.477     raeburn  3489:         my $fpath = '';
                   3490:         my $fname = $file;
1.478     albertel 3491:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3492:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3493:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3494:         if ($action eq 'copy') {
                   3495:             if ($source eq '') {
                   3496:                 $fetchresult = 'no source file';
                   3497:                 return $fetchresult;
                   3498:             } else {
                   3499:                 my $destination = $filepath.'/'.$fname;
                   3500:                 rename($source,$destination);
                   3501:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3502:                                  $home);
1.481     raeburn  3503:             }
                   3504:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3505:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3506:             print $fh $env{'form.'.$source};
1.481     raeburn  3507:             close($fh);
1.637     raeburn  3508:             if ($parser eq 'parse') {
1.1024    raeburn  3509:                 my $mm = new File::MMagic;
1.1095    raeburn  3510:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3511:                 if ($type eq 'text/html') {
1.1024    raeburn  3512:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3513:                     unless ($parse_result eq 'ok') {
                   3514:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3515:                     }
1.637     raeburn  3516:                 }
1.1095    raeburn  3517:                 if (ref($mimetype)) {
                   3518:                     $$mimetype = $type;
                   3519:                 } 
1.637     raeburn  3520:             }
1.477     raeburn  3521:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3522:                                  $home);
1.481     raeburn  3523:             if ($fetchresult eq 'ok') {
                   3524:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3525:             } else {
                   3526:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3527:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3528:                 return '/adm/notfound.html';
                   3529:             }
1.477     raeburn  3530:         }
                   3531:     }
1.485     raeburn  3532:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3533:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3534:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3535:     }
                   3536:     return $fetchresult;
                   3537: }
                   3538: 
1.637     raeburn  3539: sub build_filepath {
                   3540:     my ($fpath) = @_;
                   3541:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3542:     unless ($fpath eq '') {
                   3543:         my @parts=split('/',$fpath);
                   3544:         foreach my $part (@parts) {
                   3545:             $filepath.= '/'.$part;
                   3546:             if ((-e $filepath)!=1) {
                   3547:                 mkdir($filepath,0777);
                   3548:             }
                   3549:         }
                   3550:     }
                   3551:     return $filepath;
                   3552: }
                   3553: 
                   3554: sub store_edited_file {
1.638     albertel 3555:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3556:     my $file = $primary_url;
                   3557:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3558:     my $fpath = '';
                   3559:     my $fname = $file;
                   3560:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3561:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3562:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3563:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3564:     print $fh $content;
                   3565:     close($fh);
1.638     albertel 3566:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3567:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3568: 			  $home);
1.637     raeburn  3569:     if ($$fetchresult eq 'ok') {
                   3570:         return '/uploaded/'.$fpath.'/'.$fname;
                   3571:     } else {
1.638     albertel 3572:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3573: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3574:         return '/adm/notfound.html';
                   3575:     }
                   3576: }
                   3577: 
1.531     albertel 3578: sub clean_filename {
1.831     albertel 3579:     my ($fname,$args)=@_;
1.315     www      3580: # Replace Windows backslashes by forward slashes
1.257     www      3581:     $fname=~s/\\/\//g;
1.831     albertel 3582:     if (!$args->{'keep_path'}) {
                   3583:         # Get rid of everything but the actual filename
                   3584: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3585:     }
1.315     www      3586: # Replace spaces by underscores
                   3587:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3588: # Transliterate non-ascii text to ascii
                   3589:     my $lang = &Apache::lonlocal::current_language();
                   3590:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3591: # Replace all other weird characters by nothing
1.831     albertel 3592:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3593: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3594: # numbers
                   3595:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3596:     return $fname;
                   3597: }
1.1172.2.110  raeburn  3598: 
1.1051    raeburn  3599: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3600: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3601: # image with the same aspect ratio as the original, but with dimensions which do 
                   3602: # not exceed $resizewidth and $resizeheight.
                   3603:  
1.984     neumanie 3604: sub resizeImage {
1.1051    raeburn  3605:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3606:     my $ima = Image::Magick->new;
                   3607:     my $resized;
                   3608:     if (-e $img_path) {
                   3609:         $ima->Read($img_path);
                   3610:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3611:             my $width = $ima->Get('width');
                   3612:             my $height = $ima->Get('height');
                   3613:             if ($width > $resizewidth) {
                   3614: 	        my $factor = $width/$resizewidth;
                   3615:                 my $newheight = $height/$factor;
                   3616:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3617:                 $resized = 1;
                   3618:             }
                   3619:         }
                   3620:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3621:             my $width = $ima->Get('width');
                   3622:             my $height = $ima->Get('height');
                   3623:             if ($height > $resizeheight) {
                   3624:                 my $factor = $height/$resizeheight;
                   3625:                 my $newwidth = $width/$factor;
                   3626:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3627:                 $resized = 1;
                   3628:             }
                   3629:         }
                   3630:         if ($resized) {
                   3631:             $ima->Write($img_path);
                   3632:         }
                   3633:     }
                   3634:     return;
1.977     amueller 3635: }
                   3636: 
1.608     albertel 3637: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3638: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3639: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3640: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3641: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3642: #                   if 'coursedoc': upload to the current course
                   3643: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3644: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3645: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3646: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3647: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3648: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3649: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3650: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3651: #        $allfiles - reference to hash for embedded objects
                   3652: #        $codebase - reference to hash for codebase of java objects
                   3653: #        $desuname - username for permanent storage of uploaded file
                   3654: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3655: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3656: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3657: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3658: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3659: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3660: #                    from File::MMagic.
1.858     raeburn  3661: # 
1.686     albertel 3662: # output: url of file in userspace, or error: <message> 
                   3663: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3664: 
1.531     albertel 3665: sub userfileupload {
1.1090    raeburn  3666:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3667:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3668:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3669:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3670:     $fname=&clean_filename($fname);
1.1090    raeburn  3671:     # See if there is anything left
1.257     www      3672:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3673:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3674:     if ($fname =~ /^\./) {
                   3675:         my ($s,$usec) = &gettimeofday();
                   3676:         while (length($usec) < 6) {
                   3677:             $usec = '0'.$usec;
                   3678:         }
                   3679:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3680:     }
1.1090    raeburn  3681:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3682:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3683:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3684:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3685:         my $now = time;
1.1090    raeburn  3686:         my $filepath;
1.1095    raeburn  3687:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3688:              $filepath = 'tmp/helprequests/'.$now;
                   3689:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3690:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3691:                          '_'.$env{'user.domain'}.'/pending';
                   3692:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3693:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3694:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3695:                 $docudom = $destudom;
                   3696:             } else {
                   3697:                 $docudom = $env{'user.domain'};
                   3698:             }
1.1172.2.96  raeburn  3699:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3700:                 $docuname = $destuname;
                   3701:             } else {
                   3702:                 $docuname = $env{'user.name'};
                   3703:             }
                   3704:             if (exists($env{'form.group'})) {
                   3705:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3706:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3707:             }
                   3708:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3709:             if ($context eq 'canceloverwrite') {
                   3710:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3711:                 if (-e  $tempfile) {
                   3712:                     my @info = stat($tempfile);
                   3713:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3714:                         unlink($tempfile);
                   3715:                     }
                   3716:                 }
                   3717:                 return;
1.523     raeburn  3718:             }
                   3719:         }
1.1090    raeburn  3720:         # Create the directory if not present
1.741     raeburn  3721:         my @parts=split(/\//,$filepath);
                   3722:         my $fullpath = $perlvar{'lonDaemons'};
                   3723:         for (my $i=0;$i<@parts;$i++) {
                   3724:             $fullpath .= '/'.$parts[$i];
                   3725:             if ((-e $fullpath)!=1) {
                   3726:                 mkdir($fullpath,0777);
                   3727:             }
                   3728:         }
1.1172.2.96  raeburn  3729:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3730:         print $fh $env{'form.'.$formname};
                   3731:         close($fh);
1.1090    raeburn  3732:         if ($context eq 'existingfile') {
                   3733:             my @info = stat($fullpath.'/'.$fname);
                   3734:             return ($fullpath.'/'.$fname,$info[9]);
                   3735:         } else {
                   3736:             return $fullpath.'/'.$fname;
                   3737:         }
1.523     raeburn  3738:     }
1.995     raeburn  3739:     if ($subdir eq 'scantron') {
                   3740:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3741:     } else {
1.995     raeburn  3742:         $fname="$subdir/$fname";
                   3743:     }
1.1090    raeburn  3744:     if ($context eq 'coursedoc') {
1.638     albertel 3745: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3746: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3747:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3748:             return &finishuserfileupload($docuname,$docudom,
                   3749: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3750: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3751:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3752:         } else {
1.1172.2.21  raeburn  3753:             if ($env{'form.folder'}) {
                   3754:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3755:             }
1.638     albertel 3756:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3757: 				       $fname,$formname,$parser,
1.1095    raeburn  3758: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3759:         }
1.719     banghart 3760:     } elsif (defined($destuname)) {
                   3761:         my $docuname=$destuname;
                   3762:         my $docudom=$destudom;
1.860     raeburn  3763: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3764: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3765:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3766:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3767:     } else {
1.638     albertel 3768:         my $docuname=$env{'user.name'};
                   3769:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3770:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3771:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3772:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3773:         }
1.860     raeburn  3774: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3775: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3776:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3777:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3778:     }
1.271     www      3779: }
                   3780: 
                   3781: sub finishuserfileupload {
1.860     raeburn  3782:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3783:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3784:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3785:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3786:   
1.860     raeburn  3787:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3788:     $file=$fname;
                   3789:     if ($fname=~m|/|) {
                   3790:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3791: 	$path.=$fnamepath.'/';
                   3792:     }
1.259     www      3793:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3794:     my $count;
                   3795:     for ($count=4;$count<=$#parts;$count++) {
                   3796:         $filepath.="/$parts[$count]";
                   3797:         if ((-e $filepath)!=1) {
                   3798: 	    mkdir($filepath,0777);
                   3799:         }
                   3800:     }
1.984     neumanie 3801: 
1.258     www      3802: # Save the file
                   3803:     {
1.1172.2.96  raeburn  3804: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3805: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3806: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3807: 	    return '/adm/notfound.html';
                   3808: 	}
1.1090    raeburn  3809:         if ($context eq 'overwrite') {
1.1117    foxr     3810:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3811:             my $target = $filepath.'/'.$file;
                   3812:             if (-e $source) {
                   3813:                 my @info = stat($source);
                   3814:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3815:                     unless (&File::Copy::move($source,$target)) {
                   3816:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3817:                         return "Moving from $source failed";
                   3818:                     }
                   3819:                 } else {
                   3820:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3821:                 }
                   3822:             } else {
                   3823:                 return "Temporary file: $source missing";
                   3824:             }
                   3825:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3826: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3827: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3828: 	    return '/adm/notfound.html';
                   3829: 	}
1.570     albertel 3830: 	close(FH);
1.1051    raeburn  3831:         if ($resizewidth && $resizeheight) {
                   3832:             my $mm = new File::MMagic;
                   3833:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3834:             if ($mime_type =~ m{^image/}) {
                   3835: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3836:             }  
1.977     amueller 3837: 	}
1.258     www      3838:     }
1.1152    raeburn  3839:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3840:         if (ref($mimetype)) {
                   3841:             if ($$mimetype eq '') {
                   3842:                 my $mm = new File::MMagic;
                   3843:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3844:                 $$mimetype = $type;
                   3845:             }
                   3846:         }
                   3847:     }
1.1172.2.109  raeburn  3848:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3849:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3850:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3851:                                                        $allfiles,$codebase);
                   3852:             unless ($parse_result eq 'ok') {
                   3853:                 &logthis('Failed to parse '.$filepath.$file.
                   3854: 	   	         ' for embedded media: '.$parse_result); 
                   3855:             }
1.637     raeburn  3856:         }
1.1172.2.109  raeburn  3857:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   3858:         my $format = $env{'form.scantron_format'};
                   3859:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  3860:     }
1.860     raeburn  3861:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3862:         my $input = $filepath.'/'.$file;
                   3863:         my $output = $filepath.'/'.'tn-'.$file;
                   3864:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  3865:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3866:         system({$args[0]} @args);
1.860     raeburn  3867:         if (-e $filepath.'/'.'tn-'.$file) {
                   3868:             $fetchthumb  = 1; 
                   3869:         }
                   3870:     }
1.858     raeburn  3871:  
1.259     www      3872: # Notify homeserver to grep it
                   3873: #
1.984     neumanie 3874:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3875:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3876:     if ($fetchresult eq 'ok') {
1.860     raeburn  3877:         if ($fetchthumb) {
                   3878:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3879:             if ($thumbresult ne 'ok') {
                   3880:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3881:                          $docuhome.': '.$thumbresult);
                   3882:             }
                   3883:         }
1.259     www      3884: #
1.258     www      3885: # Return the URL to it
1.494     albertel 3886:         return '/uploaded/'.$path.$file;
1.263     www      3887:     } else {
1.494     albertel 3888:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3889: 		 ': '.$fetchresult);
1.263     www      3890:         return '/adm/notfound.html';
1.858     raeburn  3891:     }
1.493     albertel 3892: }
                   3893: 
1.637     raeburn  3894: sub extract_embedded_items {
1.961     raeburn  3895:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3896:     my @state = ();
1.1164    raeburn  3897:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3898:     my %javafiles = (
                   3899:                       codebase => '',
                   3900:                       code => '',
                   3901:                       archive => ''
                   3902:                     );
                   3903:     my %mediafiles = (
                   3904:                       src => '',
                   3905:                       movie => '',
                   3906:                      );
1.648     raeburn  3907:     my $p;
                   3908:     if ($content) {
                   3909:         $p = HTML::LCParser->new($content);
                   3910:     } else {
1.961     raeburn  3911:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3912:     }
1.641     albertel 3913:     while (my $t=$p->get_token()) {
1.640     albertel 3914: 	if ($t->[0] eq 'S') {
                   3915: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3916: 	    push(@state, $tagname);
1.648     raeburn  3917:             if (lc($tagname) eq 'allow') {
                   3918:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3919:             }
1.640     albertel 3920: 	    if (lc($tagname) eq 'img') {
                   3921: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3922: 	    }
1.886     albertel 3923: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  3924:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   3925: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   3926:                 }
1.886     albertel 3927: 	    }
1.645     raeburn  3928:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3929:                 my $src;
1.645     raeburn  3930:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3931:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3932:                 } else {
1.1164    raeburn  3933:                     if ($attr->{'src'} ne '') {
                   3934:                         $src = $attr->{'src'};
                   3935:                         &add_filetype($allfiles,$src,'src');
                   3936:                     }
                   3937:                 }
                   3938:                 my $text = $p->get_trimmed_text();
                   3939:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3940:                     my @swfargs = split(/,/,$1);
                   3941:                     foreach my $item (@swfargs) {
                   3942:                         $item =~ s/["']//g;
                   3943:                         $item =~ s/^\s+//;
                   3944:                         $item =~ s/\s+$//;
                   3945:                     }
                   3946:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3947:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3948:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3949:                         } else {
                   3950:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3951:                         }
                   3952:                     }
1.645     raeburn  3953:                 }
                   3954:             }
                   3955:             if (lc($tagname) eq 'link') {
                   3956:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3957:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3958:                 }
                   3959:             }
1.640     albertel 3960: 	    if (lc($tagname) eq 'object' ||
                   3961: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3962: 		foreach my $item (keys(%javafiles)) {
                   3963: 		    $javafiles{$item} = '';
                   3964: 		}
1.1164    raeburn  3965:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3966:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3967:                 }
1.640     albertel 3968: 	    }
                   3969: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3970: 		my $name = lc($attr->{'name'});
                   3971: 		foreach my $item (keys(%javafiles)) {
                   3972: 		    if ($name eq $item) {
                   3973: 			$javafiles{$item} = $attr->{'value'};
                   3974: 			last;
                   3975: 		    }
                   3976: 		}
1.1164    raeburn  3977:                 my $pathfrom;
1.640     albertel 3978: 		foreach my $item (keys(%mediafiles)) {
                   3979: 		    if ($name eq $item) {
1.1164    raeburn  3980:                         $pathfrom = $attr->{'value'};
                   3981:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3982: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3983: 			last;
                   3984: 		    }
                   3985: 		}
1.1164    raeburn  3986:                 if ($name eq 'flashvars') {
                   3987:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3988:                 }
                   3989:                 if ($pathfrom ne '') {
                   3990:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3991:                                          $pathfrom);
                   3992:                 }
1.640     albertel 3993: 	    }
                   3994: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3995: 		foreach my $item (keys(%javafiles)) {
                   3996: 		    if ($attr->{$item}) {
                   3997: 			$javafiles{$item} = $attr->{$item};
                   3998: 			last;
                   3999: 		    }
                   4000: 		}
                   4001: 		foreach my $item (keys(%mediafiles)) {
                   4002: 		    if ($attr->{$item}) {
                   4003: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4004: 			last;
                   4005: 		    }
                   4006: 		}
1.1164    raeburn  4007:                 if (lc($tagname) eq 'embed') {
                   4008:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4009:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4010:                                              $attr->{'src'});
                   4011:                     }
                   4012:                 }
1.640     albertel 4013: 	    }
1.1172.2.35  raeburn  4014:             if (lc($tagname) eq 'iframe') {
                   4015:                 my $src = $attr->{'src'} ;
                   4016:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4017:                     &add_filetype($allfiles,$src,'src');
                   4018:                 } elsif ($src =~ m{^/}) {
                   4019:                     if ($env{'request.course.id'}) {
                   4020:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4021:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4022:                         my $url = &hreflocation('',$fullpath);
                   4023:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4024:                             my $relpath = $1;
                   4025:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4026:                                 &add_filetype($allfiles,$1,'src');
                   4027:                             }
                   4028:                         }
                   4029:                     }
                   4030:                 }
                   4031:             }
1.1164    raeburn  4032:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4033:                 pop(@state);
1.1164    raeburn  4034:             }
1.640     albertel 4035: 	} elsif ($t->[0] eq 'E') {
                   4036: 	    my ($tagname) = ($t->[1]);
                   4037: 	    if ($javafiles{'codebase'} ne '') {
                   4038: 		$javafiles{'codebase'} .= '/';
                   4039: 	    }  
                   4040: 	    if (lc($tagname) eq 'applet' ||
                   4041: 		lc($tagname) eq 'object' ||
                   4042: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4043: 		) {
                   4044: 		foreach my $item (keys(%javafiles)) {
                   4045: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4046: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4047: 			&add_filetype($allfiles,$file,$item);
                   4048: 		    }
                   4049: 		}
                   4050: 	    } 
                   4051: 	    pop @state;
                   4052: 	}
                   4053:     }
1.1164    raeburn  4054:     foreach my $id (sort(keys(%flashvars))) {
                   4055:         if ($shockwave{$id} ne '') {
                   4056:             my @pairs = split(/\&/,$flashvars{$id});
                   4057:             foreach my $pair (@pairs) {
                   4058:                 my ($key,$value) = split(/\=/,$pair);
                   4059:                 if ($key eq 'thumb') {
                   4060:                     &add_filetype($allfiles,$value,$key);
                   4061:                 } elsif ($key eq 'content') {
                   4062:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4063:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4064:                     if ($ext ne '') {
                   4065:                         &add_filetype($allfiles,$path.$value,$ext);
                   4066:                     }
                   4067:                 }
                   4068:             }
                   4069:         }
                   4070:     }
1.637     raeburn  4071:     return 'ok';
                   4072: }
                   4073: 
1.639     albertel 4074: sub add_filetype {
                   4075:     my ($allfiles,$file,$type)=@_;
                   4076:     if (exists($allfiles->{$file})) {
                   4077: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4078: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4079: 	}
                   4080:     } else {
                   4081: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4082:     }
                   4083: }
                   4084: 
1.1164    raeburn  4085: sub embedded_dependency {
                   4086:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4087:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4088:         if (($identifier ne '') &&
                   4089:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4090:             ($pathfrom ne '')) {
                   4091:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4092:             foreach my $dep (@{$related->{$identifier}}) {
                   4093:                 &add_filetype($allfiles,$path.$dep,'object');
                   4094:             }
                   4095:         }
                   4096:     }
                   4097:     return;
                   4098: }
                   4099: 
1.1172.2.109  raeburn  4100: sub bubblesheet_converter {
                   4101:     my ($cdom,$fullpath,$config,$format) = @_;
                   4102:     if ((&domain($cdom) ne '') &&
                   4103:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4104:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4105:         my (%csvcols,%csvoptions);
                   4106:         if (ref($config->{'fields'}) eq 'HASH') {
                   4107:             %csvcols = %{$config->{'fields'}};
                   4108:         }
                   4109:         if (ref($config->{'options'}) eq 'HASH') {
                   4110:             %csvoptions = %{$config->{'options'}};
                   4111:         }
                   4112:         my %csvbynum = reverse(%csvcols);
                   4113:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4114:         if (keys(%scantronconf)) {
                   4115:             my %bynum = (
                   4116:                           $scantronconf{CODEstart} => 'CODEstart',
                   4117:                           $scantronconf{IDstart}   => 'IDstart',
                   4118:                           $scantronconf{PaperID}   => 'PaperID',
                   4119:                           $scantronconf{FirstName} => 'FirstName',
                   4120:                           $scantronconf{LastName}  => 'LastName',
                   4121:                           $scantronconf{Qstart}    => 'Qstart',
                   4122:                         );
                   4123:             my @ordered;
                   4124:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4125:                 push(@ordered,$bynum{$item});
                   4126:             }
                   4127:             my %mapstart = (
                   4128:                               CODEstart => 'CODE',
                   4129:                               IDstart   => 'ID',
                   4130:                               PaperID   => 'PaperID',
                   4131:                               FirstName => 'FirstName',
                   4132:                               LastName  => 'LastName',
                   4133:                               Qstart    => 'FirstQuestion',
                   4134:                            );
                   4135:             my %maplength = (
                   4136:                               CODEstart => 'CODElength',
                   4137:                               IDstart   => 'IDlength',
                   4138:                               PaperID   => 'PaperIDlength',
                   4139:                               FirstName => 'FirstNamelength',
                   4140:                               LastName  => 'LastNamelength',
                   4141:             );
                   4142:             if (open(my $fh,'<',$fullpath)) {
                   4143:                 my $output;
                   4144:                 my %lettdig = &letter_to_digits();
                   4145:                 my %diglett = reverse(%lettdig);
                   4146:                 my $numletts = scalar(keys(%lettdig));
                   4147:                 my $num = 0;
                   4148:                 while (my $line=<$fh>) {
                   4149:                     $num ++;
                   4150:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4151:                     $line =~ s{[\r\n]+$}{};
                   4152:                     my %found;
                   4153:                     my @values = split(/,/,$line);
                   4154:                     my ($qstart,$record);
                   4155:                     for (my $i=0; $i<@values; $i++) {
                   4156:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4157:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4158:                             if ($values[$i] eq '') {
                   4159:                                 $values[$i] = $scantronconf{'Qoff'};
                   4160:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4161:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4162:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4163:                                 }
                   4164:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4165:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4166:                                     $values[$i] = $diglett{$values[$i]};
                   4167:                                 }
                   4168:                             } else {
                   4169:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4170:                                     my $digit;
                   4171:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4172:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4173:                                         if ($values[$i] eq 'J') {
                   4174:                                             $digit += $numletts;
                   4175:                                         }
                   4176:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4177:                                         $digit = $values[$i]-1;
                   4178:                                         if ($values[$i] eq '0') {
                   4179:                                             $digit += $numletts;
                   4180:                                         }
                   4181:                                     }
                   4182:                                     my $qval='';
                   4183:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4184:                                         if ($j == $digit) {
                   4185:                                             $qval .= $scantronconf{'Qon'};
                   4186:                                         } else {
                   4187:                                             $qval .= $scantronconf{'Qoff'};
                   4188:                                         }
                   4189:                                     }
                   4190:                                     $values[$i] = $qval;
                   4191:                                 }
                   4192:                             }
                   4193:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4194:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4195:                             }
                   4196:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4197:                             if ($numblank > 0) {
                   4198:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4199:                             }
                   4200:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4201:                                 $qstart = $i;
                   4202:                                 $found{$csvbynum{$i}} = $values[$i];
                   4203:                             } else {
                   4204:                                 $found{'FirstQuestion'} .= $values[$i];
                   4205:                             }
                   4206:                         } elsif (exists($csvbynum{$i})) {
                   4207:                             if ($csvoptions{'rem'}) {
                   4208:                                 $values[$i] =~ s/^\s+//;
                   4209:                             }
                   4210:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4211:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4212:                                     $values[$i] = '0'.$values[$i];
                   4213:                                 }
                   4214:                             }
                   4215:                             $found{$csvbynum{$i}} = $values[$i];
                   4216:                         }
                   4217:                     }
                   4218:                     foreach my $item (@ordered) {
                   4219:                         my $currlength = 1+length($record);
                   4220:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4221:                         if ($numspaces > 0) {
                   4222:                             $record .= (' ' x $numspaces);
                   4223:                         }
                   4224:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4225:                             unless ($item eq 'Qstart') {
                   4226:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4227:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4228:                                 }
                   4229:                             }
                   4230:                             $record .= $found{$mapstart{$item}};
                   4231:                         }
                   4232:                     }
                   4233:                     $output .= "$record\n";
                   4234:                 }
                   4235:                 close($fh);
                   4236:                 if ($output) {
                   4237:                     if (open(my $fh,'>',$fullpath)) {
                   4238:                         print $fh $output;
                   4239:                         close($fh);
                   4240:                     }
                   4241:                 }
                   4242:             }
                   4243:         }
                   4244:         return;
                   4245:     }
                   4246: }
                   4247: 
                   4248: sub letter_to_digits {
                   4249:     my %lettdig = (
                   4250:                     A => 1,
                   4251:                     B => 2,
                   4252:                     C => 3,
                   4253:                     D => 4,
                   4254:                     E => 5,
                   4255:                     F => 6,
                   4256:                     G => 7,
                   4257:                     H => 8,
                   4258:                     I => 9,
                   4259:                     J => 0,
                   4260:                   );
                   4261:     return %lettdig;
                   4262: }
                   4263: 
                   4264: sub get_scantron_config {
                   4265:     my ($which,$cdom) = @_;
                   4266:     my @lines = &get_scantronformat_file($cdom);
                   4267:     my %config;
                   4268:     #FIXME probably should move to XML it has already gotten a bit much now
                   4269:     foreach my $line (@lines) {
                   4270:         my ($name,$descrip)=split(/:/,$line);
                   4271:         if ($name ne $which ) { next; }
                   4272:         chomp($line);
                   4273:         my @config=split(/:/,$line);
                   4274:         $config{'name'}=$config[0];
                   4275:         $config{'description'}=$config[1];
                   4276:         $config{'CODElocation'}=$config[2];
                   4277:         $config{'CODEstart'}=$config[3];
                   4278:         $config{'CODElength'}=$config[4];
                   4279:         $config{'IDstart'}=$config[5];
                   4280:         $config{'IDlength'}=$config[6];
                   4281:         $config{'Qstart'}=$config[7];
                   4282:         $config{'Qlength'}=$config[8];
                   4283:         $config{'Qoff'}=$config[9];
                   4284:         $config{'Qon'}=$config[10];
                   4285:         $config{'PaperID'}=$config[11];
                   4286:         $config{'PaperIDlength'}=$config[12];
                   4287:         $config{'FirstName'}=$config[13];
                   4288:         $config{'FirstNamelength'}=$config[14];
                   4289:         $config{'LastName'}=$config[15];
                   4290:         $config{'LastNamelength'}=$config[16];
                   4291:         $config{'BubblesPerRow'}=$config[17];
                   4292:         last;
                   4293:     }
                   4294:     return %config;
                   4295: }
                   4296: 
                   4297: sub get_scantronformat_file {
                   4298:     my ($cdom) = @_;
                   4299:     if ($cdom eq '') {
                   4300:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4301:     }
                   4302:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4303:     my $gottab = 0;
                   4304:     my @lines;
                   4305:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4306:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4307:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4308:             if ($formatfile ne '-1') {
                   4309:                 @lines = split("\n",$formatfile,-1);
                   4310:                 $gottab = 1;
                   4311:             }
                   4312:         }
                   4313:     }
                   4314:     if (!$gottab) {
                   4315:         my $confname = $cdom.'-domainconfig';
                   4316:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4317:         my $formatfile = &getfile($default);
                   4318:         if ($formatfile ne '-1') {
                   4319:             @lines = split("\n",$formatfile,-1);
                   4320:             $gottab = 1;
                   4321:         }
                   4322:     }
                   4323:     if (!$gottab) {
                   4324:         my @domains = &current_machine_domains();
                   4325:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4326:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4327:                 @lines = <$fh>;
                   4328:                 close($fh);
                   4329:             }
                   4330:         } else {
                   4331:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4332:                 @lines = <$fh>;
                   4333:                 close($fh);
                   4334:             }
                   4335:         }
                   4336:     }
                   4337:     return @lines;
                   4338: }
                   4339: 
1.493     albertel 4340: sub removeuploadedurl {
1.984     neumanie 4341:     my ($url)=@_;	
                   4342:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4343:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4344: }
                   4345: 
                   4346: sub removeuserfile {
                   4347:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4348:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4349:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4350:     if ($result eq 'ok') {	
1.798     raeburn  4351:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4352:             my $metafile = $fname.'.meta';
                   4353:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4354: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4355:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4356:             my $sqlresult = 
1.823     albertel 4357:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4358:                                         'portfolio_metadata',$group,
                   4359:                                         'delete');
1.798     raeburn  4360:         }
                   4361:     }
                   4362:     return $result;
1.257     www      4363: }
1.15      www      4364: 
1.530     albertel 4365: sub mkdiruserfile {
                   4366:     my ($docuname,$docudom,$dir)=@_;
                   4367:     my $home=&homeserver($docuname,$docudom);
                   4368:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4369: }
                   4370: 
1.531     albertel 4371: sub renameuserfile {
                   4372:     my ($docuname,$docudom,$old,$new)=@_;
                   4373:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4374:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4375:                         &escape("$old").':'.&escape("$new"),$home);
                   4376:     if ($result eq 'ok') {
                   4377:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4378:             my $oldmeta = $old.'.meta';
                   4379:             my $newmeta = $new.'.meta';
                   4380:             my $metaresult = 
                   4381:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4382: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4383:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4384:             my $sqlresult = 
1.823     albertel 4385:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4386:                                         'portfolio_metadata',$group,
                   4387:                                         'delete');
1.798     raeburn  4388:         }
                   4389:     }
                   4390:     return $result;
1.531     albertel 4391: }
                   4392: 
1.14      www      4393: # ------------------------------------------------------------------------- Log
                   4394: 
                   4395: sub log {
                   4396:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4397:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4398: }
                   4399: 
                   4400: # ------------------------------------------------------------------ Course Log
1.352     www      4401: #
                   4402: # This routine flushes several buffers of non-mission-critical nature
                   4403: #
1.157     www      4404: 
                   4405: sub flushcourselogs {
1.352     www      4406:     &logthis('Flushing log buffers');
                   4407: #
                   4408: # course logs
                   4409: # This is a log of all transactions in a course, which can be used
                   4410: # for data mining purposes
                   4411: #
                   4412: # It also collects the courseid database, which lists last transaction
                   4413: # times and course titles for all courseids
                   4414: #
                   4415:     my %courseidbuffer=();
1.921     raeburn  4416:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4417:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4418: 		          &escape($courselogs{$crsid}),
                   4419: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4420: 	    delete $courselogs{$crsid};
                   4421:         } else {
                   4422:             &logthis('Failed to flush log buffer for '.$crsid);
                   4423:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4424:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4425:                         " exceeded maximum size, deleting.</font>");
                   4426:                delete $courselogs{$crsid};
                   4427:             }
1.352     www      4428:         }
1.920     raeburn  4429:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4430:             'description' => $coursedescrbuf{$crsid},
                   4431:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4432:             'type'        => $coursetypebuf{$crsid},
                   4433:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4434:         };
1.191     harris41 4435:     }
1.352     www      4436: #
                   4437: # Write course id database (reverse lookup) to homeserver of courses 
                   4438: # Is used in pickcourse
                   4439: #
1.840     albertel 4440:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4441:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4442:                                     $courseidbuffer{$crs_home},
                   4443:                                     $crs_home,'timeonly');
1.352     www      4444:     }
                   4445: #
                   4446: # File accesses
                   4447: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4448: #
1.449     matthew  4449:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4450:         if ($entry =~ /___count$/) {
                   4451:             my ($dom,$name);
1.807     albertel 4452:             ($dom,$name,undef)=
1.811     albertel 4453: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4454:             if (! defined($dom) || $dom eq '' || 
                   4455:                 ! defined($name) || $name eq '') {
1.620     albertel 4456:                 my $cid = $env{'request.course.id'};
                   4457:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4458:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4459:             }
1.450     matthew  4460:             my $value = $accesshash{$entry};
                   4461:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4462:             my %temphash=($url => $value);
1.449     matthew  4463:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4464:             if ($result eq 'ok') {
                   4465:                 delete $accesshash{$entry};
                   4466:             }
                   4467:         } else {
1.811     albertel 4468:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4469:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4470:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4471:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4472:                 delete $accesshash{$entry};
                   4473:             }
1.185     www      4474:         }
1.191     harris41 4475:     }
1.352     www      4476: #
                   4477: # Roles
                   4478: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4479: #
1.800     albertel 4480:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4481:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4482: 	    split(/\:/,$entry);
                   4483:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4484:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4485:                 $rudom,$runame) eq 'ok') {
                   4486: 	    delete $userrolehash{$entry};
                   4487:         }
                   4488:     }
1.662     raeburn  4489: #
1.1172.2.90  raeburn  4490: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4491: #
                   4492:     my %domrolebuffer = ();
1.1000    raeburn  4493:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4494:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4495:         if ($domrolebuffer{$rudom}) {
                   4496:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4497:                       '='.&escape($domainrolehash{$entry});
                   4498:         } else {
                   4499:             $domrolebuffer{$rudom}.=&escape($entry).
                   4500:                       '='.&escape($domainrolehash{$entry});
                   4501:         }
                   4502:         delete $domainrolehash{$entry};
                   4503:     }
                   4504:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4505:         my %servers;
                   4506:         if (defined(&domain($dom,'primary'))) {
                   4507:             my $primary=&domain($dom,'primary');
                   4508:             my $hostname=&hostname($primary);
                   4509:             $servers{$primary} = $hostname;
                   4510:         } else {
                   4511:             %servers = &get_servers($dom,'library');
                   4512:         }
1.841     albertel 4513: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4514: 	    if (&reply('domroleput:'.$dom.':'.
                   4515: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4516: 	        last;
                   4517: 	    } else {
1.841     albertel 4518: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4519: 	    }
1.662     raeburn  4520:         }
                   4521:     }
1.186     www      4522:     $dumpcount++;
1.157     www      4523: }
                   4524: 
                   4525: sub courselog {
                   4526:     my $what=shift;
1.158     www      4527:     $what=time.':'.$what;
1.620     albertel 4528:     unless ($env{'request.course.id'}) { return ''; }
                   4529:     $coursedombuf{$env{'request.course.id'}}=
                   4530:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4531:     $coursenumbuf{$env{'request.course.id'}}=
                   4532:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4533:     $coursehombuf{$env{'request.course.id'}}=
                   4534:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4535:     $coursedescrbuf{$env{'request.course.id'}}=
                   4536:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4537:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4538:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4539:     $courseownerbuf{$env{'request.course.id'}}=
                   4540:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4541:     $coursetypebuf{$env{'request.course.id'}}=
                   4542:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4543:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4544: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4545:     } else {
1.620     albertel 4546: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4547:     }
1.620     albertel 4548:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4549: 	&flushcourselogs();
                   4550:     }
1.158     www      4551: }
                   4552: 
                   4553: sub courseacclog {
                   4554:     my $fnsymb=shift;
1.620     albertel 4555:     unless ($env{'request.course.id'}) { return ''; }
                   4556:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4557:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4558:         $what.=':POST';
1.583     matthew  4559:         # FIXME: Probably ought to escape things....
1.800     albertel 4560: 	foreach my $key (keys(%env)) {
                   4561:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4562:                 my $formitem = $1;
                   4563:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4564:                     $what.=':'.$formitem.'='.$env{$key};
                   4565:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4566:                     $what.=':'.$formitem.'='.$env{$key};
                   4567:                 }
1.158     www      4568:             }
1.191     harris41 4569:         }
1.583     matthew  4570:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4571:         # FIXME: We should not be depending on a form parameter that someone
                   4572:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4573:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4574:             $what.= ':POST';
                   4575:             # FIXME: Probably ought to escape things....
                   4576:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4577:                                  'crsdiscuss') {
1.620     albertel 4578:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4579:             }
                   4580:         }
1.158     www      4581:     }
                   4582:     &courselog($what);
1.149     www      4583: }
                   4584: 
1.185     www      4585: sub countacc {
                   4586:     my $url=&declutter(shift);
1.458     matthew  4587:     return if (! defined($url) || $url eq '');
1.620     albertel 4588:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4589: #
                   4590: # Mark that this url was used in this course
                   4591: #
1.620     albertel 4592:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4593: #
                   4594: # Increase the access count for this resource in this child process
                   4595: #
1.281     www      4596:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4597:     $accesshash{$key}++;
1.185     www      4598: }
1.349     www      4599: 
1.361     www      4600: sub linklog {
                   4601:     my ($from,$to)=@_;
                   4602:     $from=&declutter($from);
                   4603:     $to=&declutter($to);
                   4604:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4605:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4606: }
1.1160    www      4607: 
                   4608: sub statslog {
                   4609:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4610:     if ($users<2) { return; }
                   4611:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4612:             'course'       => $env{'request.course.id'},
                   4613:             'sections'     => '"all"',
                   4614:             'num_students' => $users,
                   4615:             'part'         => $part,
                   4616:             'symb'         => $symb,
                   4617:             'mean_tries'   => $av_attempts,
                   4618:             'deg_of_diff'  => $degdiff});
                   4619:     foreach my $key (keys(%dynstore)) {
                   4620:         $accesshash{$key}=$dynstore{$key};
                   4621:     }
                   4622: }
1.361     www      4623:   
1.349     www      4624: sub userrolelog {
                   4625:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4626:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4627:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4628:        $userrolehash
                   4629:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4630:                     =$tend.':'.$tstart;
1.662     raeburn  4631:     }
1.1169    droeschl 4632:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4633:        $userrolehash
                   4634:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4635:                     =$tend.':'.$tstart;
                   4636:     }
1.1172.2.90  raeburn  4637:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4638:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4639:        $domainrolehash
                   4640:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4641:                     = $tend.':'.$tstart;
                   4642:     }
1.351     www      4643: }
                   4644: 
1.957     raeburn  4645: sub courserolelog {
                   4646:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4647:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4648:         my $cdom = $1;
                   4649:         my $cnum = $2;
                   4650:         my $sec = $3;
                   4651:         my $namespace = 'rolelog';
                   4652:         my %storehash = (
                   4653:                            role    => $trole,
                   4654:                            start   => $tstart,
                   4655:                            end     => $tend,
                   4656:                            selfenroll => $selfenroll,
                   4657:                            context    => $context,
                   4658:                         );
                   4659:         if ($trole eq 'gr') {
                   4660:             $namespace = 'groupslog';
                   4661:             $storehash{'group'} = $sec;
                   4662:         } else {
                   4663:             $storehash{'section'} = $sec;
                   4664:         }
                   4665:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4666:                    $domain,$cnum,$cdom);
                   4667:         if (($trole ne 'st') || ($sec ne '')) {
                   4668:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4669:         }
                   4670:     }
                   4671:     return;
                   4672: }
                   4673: 
1.1172.2.9  raeburn  4674: sub domainrolelog {
                   4675:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4676:     if ($area =~ m{^/($match_domain)/$}) {
                   4677:         my $cdom = $1;
                   4678:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4679:         my $namespace = 'rolelog';
                   4680:         my %storehash = (
                   4681:                            role    => $trole,
                   4682:                            start   => $tstart,
                   4683:                            end     => $tend,
                   4684:                            context => $context,
                   4685:                         );
                   4686:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4687:                    $domain,$domconfiguser,$cdom);
                   4688:     }
                   4689:     return;
                   4690: 
                   4691: }
                   4692: 
                   4693: sub coauthorrolelog {
                   4694:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4695:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4696:         my $audom = $1;
                   4697:         my $auname = $2;
                   4698:         my $namespace = 'rolelog';
                   4699:         my %storehash = (
                   4700:                            role    => $trole,
                   4701:                            start   => $tstart,
                   4702:                            end     => $tend,
                   4703:                            context => $context,
                   4704:                         );
                   4705:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4706:                    $domain,$auname,$audom);
                   4707:     }
                   4708:     return;
                   4709: }
                   4710: 
1.351     www      4711: sub get_course_adv_roles {
1.948     raeburn  4712:     my ($cid,$codes) = @_;
1.620     albertel 4713:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4714:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4715:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4716:     my %nothide=();
1.800     albertel 4717:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4718:         if ($user !~ /:/) {
                   4719: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4720:         } else {
                   4721:             $nothide{$user}=1;
                   4722:         }
1.470     www      4723:     }
1.1172.2.23  raeburn  4724:     my @possdoms = ($coursehash{'domain'});
                   4725:     if ($coursehash{'checkforpriv'}) {
                   4726:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4727:     }
1.351     www      4728:     my %returnhash=();
                   4729:     my %dumphash=
                   4730:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4731:     my $now=time;
1.997     raeburn  4732:     my %privileged;
1.1000    raeburn  4733:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4734: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4735:         if (($tstart) && ($tstart<0)) { next; }
                   4736:         if (($tend) && ($tend<$now)) { next; }
                   4737:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4738:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4739: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4740:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4741:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4742: 	if ($role eq 'cr') { next; }
1.948     raeburn  4743:         if ($codes) {
                   4744:             if ($section) { $role .= ':'.$section; }
                   4745:             if ($returnhash{$role}) {
                   4746:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4747:             } else {
                   4748:                 $returnhash{$role}=$username.':'.$domain;
                   4749:             }
1.351     www      4750:         } else {
1.988     raeburn  4751:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4752:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4753:             if ($returnhash{$key}) {
                   4754: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4755:             } else {
                   4756:                 $returnhash{$key}=$username.':'.$domain;
                   4757:             }
1.351     www      4758:         }
1.948     raeburn  4759:     }
1.400     www      4760:     return %returnhash;
                   4761: }
                   4762: 
                   4763: sub get_my_roles {
1.937     raeburn  4764:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4765:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4766:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4767:     my (%dumphash,%nothide);
1.1086    raeburn  4768:     if ($context eq 'userroles') {
1.1166    raeburn  4769:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4770:     } else {
1.1172.2.23  raeburn  4771:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4772:         if ($hidepriv) {
                   4773:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4774:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4775:                 if ($user !~ /:/) {
                   4776:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4777:                 } else {
                   4778:                     $nothide{$user} = 1;
                   4779:                 }
                   4780:             }
                   4781:         }
1.858     raeburn  4782:     }
1.400     www      4783:     my %returnhash=();
                   4784:     my $now=time;
1.999     raeburn  4785:     my %privileged;
1.800     albertel 4786:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4787:         my ($role,$tend,$tstart);
                   4788:         if ($context eq 'userroles') {
1.1149    raeburn  4789:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4790: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4791:         } else {
                   4792:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4793:         }
1.400     www      4794:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4795:         my $status = 'active';
1.939     raeburn  4796:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4797:             $status = 'previous';
                   4798:         } 
                   4799:         if (($tstart) && ($now<$tstart)) {
                   4800:             $status = 'future';
                   4801:         }
                   4802:         if (ref($types) eq 'ARRAY') {
                   4803:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4804:                 next;
                   4805:             } 
                   4806:         } else {
                   4807:             if ($status ne 'active') {
                   4808:                 next;
                   4809:             }
                   4810:         }
1.867     raeburn  4811:         my ($rolecode,$username,$domain,$section,$area);
                   4812:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4813:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4814:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4815:         } else {
                   4816:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4817:         }
1.832     raeburn  4818:         if (ref($roledoms) eq 'ARRAY') {
                   4819:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4820:                 next;
                   4821:             }
                   4822:         }
                   4823:         if (ref($roles) eq 'ARRAY') {
                   4824:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4825:                 if ($role =~ /^cr\//) {
                   4826:                     if (!grep(/^cr$/,@{$roles})) {
                   4827:                         next;
                   4828:                     }
1.1104    raeburn  4829:                 } elsif ($role =~ /^gr\//) {
                   4830:                     if (!grep(/^gr$/,@{$roles})) {
                   4831:                         next;
                   4832:                     }
1.922     raeburn  4833:                 } else {
                   4834:                     next;
                   4835:                 }
1.832     raeburn  4836:             }
1.867     raeburn  4837:         }
1.937     raeburn  4838:         if ($hidepriv) {
1.1172.2.23  raeburn  4839:             my @privroles = ('dc','su');
1.999     raeburn  4840:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4841:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4842:             } else {
1.1172.2.23  raeburn  4843:                 my $possdoms = [$domain];
                   4844:                 if (ref($roledoms) eq 'ARRAY') {
                   4845:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4846:                 }
1.1172.2.23  raeburn  4847:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4848:                     if (!$nothide{$username.':'.$domain}) {
                   4849:                         next;
                   4850:                     }
                   4851:                 }
1.937     raeburn  4852:             }
                   4853:         }
1.933     raeburn  4854:         if ($withsec) {
                   4855:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4856:                 $tstart.':'.$tend;
                   4857:         } else {
                   4858:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4859:         }
1.832     raeburn  4860:     }
1.373     www      4861:     return %returnhash;
1.399     www      4862: }
                   4863: 
1.1172.2.89  raeburn  4864: sub get_all_adhocroles {
                   4865:     my ($dom) = @_;
                   4866:     my @roles_by_num = ();
                   4867:     my %domdefaults = &get_domain_defaults($dom);
                   4868:     my (%description,%access_in_dom,%access_info);
                   4869:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4870:         my $count = 0;
                   4871:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4872:         my %ordered;
                   4873:         foreach my $role (sort(keys(%domcurrent))) {
                   4874:             my ($order,$desc,$access_in_dom);
                   4875:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4876:                 $order = $domcurrent{$role}{'order'};
                   4877:                 $desc = $domcurrent{$role}{'desc'};
                   4878:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4879:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4880:             }
                   4881:             if ($order eq '') {
                   4882:                 $order = $count;
                   4883:             }
                   4884:             $ordered{$order} = $role;
                   4885:             if ($desc ne '') {
                   4886:                 $description{$role} = $desc;
                   4887:             } else {
                   4888:                 $description{$role}= $role;
                   4889:             }
                   4890:             $count++;
                   4891:         }
                   4892:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4893:             push(@roles_by_num,$ordered{$item});
                   4894:         }
                   4895:     }
                   4896:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4897: }
                   4898: 
                   4899: sub get_my_adhocroles {
                   4900:     my ($cid,$checkreg) = @_;
                   4901:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4902:     if ($env{'request.course.id'} eq $cid) {
                   4903:         $cdom = $env{'course.'.$cid.'.domain'};
                   4904:         $cnum = $env{'course.'.$cid.'.num'};
                   4905:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4906:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4907:         $cdom = $1;
                   4908:         $cnum = $2;
                   4909:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4910:                                      $cdom,$cnum);
                   4911:     }
                   4912:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4913:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4914:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4915:         if ($rosterhash{$user} ne '') {
                   4916:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4917:             return ([],{}) if ($type eq 'auto');
                   4918:         }
                   4919:     }
                   4920:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  4921:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  4922:             my $then=$env{'user.login.time'};
                   4923:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  4924:             if (!$update) {
                   4925:                 $update = $then;
                   4926:             }
                   4927:             my @liveroles;
                   4928:             foreach my $role ('dh','da') {
                   4929:                 if ($env{"user.role.$role./$cdom/"}) {
                   4930:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   4931:                     my $limit = $update;
                   4932:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4933:                         $limit = $then;
                   4934:                     }
                   4935:                     my $activerole = 1;
                   4936:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4937:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4938:                     if ($activerole) {
                   4939:                         push(@liveroles,$role);
                   4940:                     }
                   4941:                 }
                   4942:             }
                   4943:             if (@liveroles) {
1.1172.2.89  raeburn  4944:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   4945:                     my ($accessref,$accessinfo,%access_in_dom);
                   4946:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4947:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4948:                         if (@{$roles_by_num}) {
                   4949:                             my %settings;
                   4950:                             if ($env{'request.course.id'} eq $cid) {
                   4951:                                 foreach my $envkey (keys(%env)) {
                   4952:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4953:                                         $settings{$1} = $env{$envkey};
                   4954:                                     }
                   4955:                                 }
                   4956:                             } else {
                   4957:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4958:                             }
                   4959:                             my %setincrs;
                   4960:                             if ($settings{'internal.adhocaccess'}) {
                   4961:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4962:                             }
                   4963:                             my @statuses;
                   4964:                             if ($env{'environment.inststatus'}) {
                   4965:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4966:                             }
                   4967:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4968:                             if (ref($accessref) eq 'HASH') {
                   4969:                                 %access_in_dom = %{$accessref};
                   4970:                             }
                   4971:                             foreach my $role (@{$roles_by_num}) {
                   4972:                                 my ($curraccess,@okstatus,@personnel);
                   4973:                                 if ($setincrs{$role}) {
                   4974:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4975:                                     if ($curraccess eq 'status') {
                   4976:                                         @okstatus = split(/\&/,$rest);
                   4977:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4978:                                         @personnel = split(/\&/,$rest);
                   4979:                                     }
                   4980:                                 } else {
                   4981:                                     $curraccess = $access_in_dom{$role};
                   4982:                                     if (ref($accessinfo) eq 'HASH') {
                   4983:                                         if ($curraccess eq 'status') {
                   4984:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4985:                                                 @okstatus = @{$accessinfo->{$role}};
                   4986:                                             }
                   4987:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4988:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4989:                                                 @personnel = @{$accessinfo->{$role}};
                   4990:                                             }
                   4991:                                         }
                   4992:                                     }
                   4993:                                 }
                   4994:                                 if ($curraccess eq 'none') {
                   4995:                                     next;
                   4996:                                 } elsif ($curraccess eq 'all') {
                   4997:                                     push(@possroles,$role);
1.1172.2.90  raeburn  4998:                                 } elsif ($curraccess eq 'dh') {
                   4999:                                     if (grep(/^dh$/,@liveroles)) {
                   5000:                                         push(@possroles,$role);
                   5001:                                     } else {
                   5002:                                         next;
                   5003:                                     }
                   5004:                                 } elsif ($curraccess eq 'da') {
                   5005:                                     if (grep(/^da$/,@liveroles)) {
                   5006:                                         push(@possroles,$role);
                   5007:                                     } else {
                   5008:                                         next;
                   5009:                                     }
1.1172.2.89  raeburn  5010:                                 } elsif ($curraccess eq 'status') {
                   5011:                                     if (@okstatus) {
                   5012:                                         if (!@statuses) {
                   5013:                                             if (grep(/^default$/,@okstatus)) {
                   5014:                                                 push(@possroles,$role);
                   5015:                                             }
                   5016:                                         } else {
                   5017:                                             foreach my $status (@okstatus) {
                   5018:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5019:                                                     push(@possroles,$role);
                   5020:                                                     last;
                   5021:                                                 }
                   5022:                                             }
                   5023:                                         }
                   5024:                                     }
                   5025:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5026:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5027:                                         if ($curraccess eq 'exc') {
                   5028:                                             push(@possroles,$role);
                   5029:                                         }
                   5030:                                     } elsif ($curraccess eq 'inc') {
                   5031:                                         push(@possroles,$role);
                   5032:                                     }
                   5033:                                 }
                   5034:                             }
                   5035:                         }
                   5036:                     }
                   5037:                 }
                   5038:             }
                   5039:         }
                   5040:     }
                   5041:     unless (ref($description) eq 'HASH') {
                   5042:         if (ref($roles_by_num) eq 'ARRAY') {
                   5043:             my %desc;
                   5044:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5045:             $description = \%desc;
                   5046:         } else {
                   5047:             $description = {};
                   5048:         }
                   5049:     }
                   5050:     return (\@possroles,$description);
                   5051: }
                   5052: 
1.399     www      5053: # ----------------------------------------------------- Frontpage Announcements
                   5054: #
                   5055: #
                   5056: 
                   5057: sub postannounce {
                   5058:     my ($server,$text)=@_;
1.844     albertel 5059:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5060:     unless ($text=~/\w/) { $text=''; }
                   5061:     return &reply('setannounce:'.&escape($text),$server);
                   5062: }
                   5063: 
                   5064: sub getannounce {
1.448     albertel 5065: 
1.1172.2.96  raeburn  5066:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5067: 	my $announcement='';
1.800     albertel 5068: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5069: 	close($fh);
1.399     www      5070: 	if ($announcement=~/\w/) { 
                   5071: 	    return 
                   5072:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5073:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5074: 	} else {
                   5075: 	    return '';
                   5076: 	}
                   5077:     } else {
                   5078: 	return '';
                   5079:     }
1.351     www      5080: }
1.353     www      5081: 
                   5082: # ---------------------------------------------------------- Course ID routines
                   5083: # Deal with domain's nohist_courseid.db files
                   5084: #
                   5085: 
                   5086: sub courseidput {
1.921     raeburn  5087:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5088:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5089:     my $outcome;
                   5090:     if ($caller eq 'timeonly') {
                   5091:         my $cids = '';
                   5092:         foreach my $item (keys(%$storehash)) {
                   5093:             $cids.=&escape($item).'&';
                   5094:         }
                   5095:         $cids=~s/\&$//;
                   5096:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5097:                           $coursehome);       
                   5098:     } else {
                   5099:         my $items = '';
                   5100:         foreach my $item (keys(%$storehash)) {
                   5101:             $items.= &escape($item).'='.
                   5102:                      &freeze_escape($$storehash{$item}).'&';
                   5103:         }
                   5104:         $items=~s/\&$//;
                   5105:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5106:                           $coursehome);
1.918     raeburn  5107:     }
                   5108:     if ($outcome eq 'unknown_cmd') {
                   5109:         my $what;
                   5110:         foreach my $cid (keys(%$storehash)) {
                   5111:             $what .= &escape($cid).'=';
1.921     raeburn  5112:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5113:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5114:             }
                   5115:             $what =~ s/\:$/&/;
                   5116:         }
                   5117:         $what =~ s/\&$//;  
                   5118:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5119:     } else {
                   5120:         return $outcome;
                   5121:     }
1.353     www      5122: }
                   5123: 
                   5124: sub courseiddump {
1.921     raeburn  5125:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5126:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5127:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5128:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5129:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5130:     my $as_hash = 1;
                   5131:     my %returnhash;
                   5132:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5133:     my %libserv = &all_library();
                   5134:     foreach my $tryserver (keys(%libserv)) {
                   5135:         if ( (  $hostidflag == 1 
                   5136: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5137: 	     || (!defined($hostidflag)) ) {
                   5138: 
1.918     raeburn  5139: 	    if (($domfilter eq '') ||
                   5140: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5141:                 my $rep;
                   5142:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5143:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5144:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5145:                                 &escape($descfilter), &escape($instcodefilter),
                   5146:                                 &escape($ownerfilter), &escape($coursefilter),
                   5147:                                 &escape($typefilter), &escape($regexp_ok),
                   5148:                                 $as_hash, &escape($selfenrollonly),
                   5149:                                 &escape($catfilter), $showhidden, $caller,
                   5150:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5151:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5152:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5153:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5154:                 } else {
                   5155:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5156:                              $sincefilter.':'.&escape($descfilter).':'.
                   5157:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5158:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5159:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5160:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5161:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5162:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5163:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5164:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5165:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5166:                 }
                   5167: 
1.918     raeburn  5168:                 my @pairs=split(/\&/,$rep);
                   5169:                 foreach my $item (@pairs) {
                   5170:                     my ($key,$value)=split(/\=/,$item,2);
                   5171:                     $key = &unescape($key);
                   5172:                     next if ($key =~ /^error: 2 /);
                   5173:                     my $result = &thaw_unescape($value);
                   5174:                     if (ref($result) eq 'HASH') {
                   5175:                         $returnhash{$key}=$result;
                   5176:                     } else {
1.921     raeburn  5177:                         my @responses = split(/:/,$value);
                   5178:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5179:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5180:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5181:                         }
1.1008    raeburn  5182:                     }
1.353     www      5183:                 }
                   5184:             }
                   5185:         }
                   5186:     }
                   5187:     return %returnhash;
                   5188: }
                   5189: 
1.1055    raeburn  5190: sub courselastaccess {
                   5191:     my ($cdom,$cnum,$hostidref) = @_;
                   5192:     my %returnhash;
                   5193:     if ($cdom && $cnum) {
                   5194:         my $chome = &homeserver($cnum,$cdom);
                   5195:         if ($chome ne 'no_host') {
                   5196:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5197:             &extract_lastaccess(\%returnhash,$rep);
                   5198:         }
                   5199:     } else {
                   5200:         if (!$cdom) { $cdom=''; }
                   5201:         my %libserv = &all_library();
                   5202:         foreach my $tryserver (keys(%libserv)) {
                   5203:             if (ref($hostidref) eq 'ARRAY') {
                   5204:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5205:             } 
                   5206:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5207:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5208:                 &extract_lastaccess(\%returnhash,$rep);
                   5209:             }
                   5210:         }
                   5211:     }
                   5212:     return %returnhash;
                   5213: }
                   5214: 
                   5215: sub extract_lastaccess {
                   5216:     my ($returnhash,$rep) = @_;
                   5217:     if (ref($returnhash) eq 'HASH') {
                   5218:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5219:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5220:                  $rep eq '') {
                   5221:             my @pairs=split(/\&/,$rep);
                   5222:             foreach my $item (@pairs) {
                   5223:                 my ($key,$value)=split(/\=/,$item,2);
                   5224:                 $key = &unescape($key);
                   5225:                 next if ($key =~ /^error: 2 /);
                   5226:                 $returnhash->{$key} = &thaw_unescape($value);
                   5227:             }
                   5228:         }
                   5229:     }
                   5230:     return;
                   5231: }
                   5232: 
1.658     raeburn  5233: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5234: 
                   5235: sub dcmailput {
1.685     raeburn  5236:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5237:     my $status = &Apache::lonnet::critical(
1.740     www      5238:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5239:        &escape($message),$server);
1.662     raeburn  5240:     return $status;
                   5241: }
                   5242: 
1.658     raeburn  5243: sub dcmaildump {
                   5244:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5245:     my %returnhash=();
1.846     albertel 5246: 
                   5247:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5248:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5249:                                                          &escape($enddate).':';
                   5250: 	my @esc_senders=map { &escape($_)} @$senders;
                   5251: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5252: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5253:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5254:             if (($key) && ($value)) {
                   5255:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5256:             }
                   5257:         }
                   5258:     }
                   5259:     return %returnhash;
                   5260: }
1.662     raeburn  5261: # ---------------------------------------------------------- Domain roles
                   5262: 
                   5263: sub get_domain_roles {
                   5264:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5265:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5266:         $startdate = '.';
                   5267:     }
1.1018    raeburn  5268:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5269:         $enddate = '.';
                   5270:     }
1.922     raeburn  5271:     my $rolelist;
                   5272:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5273:         $rolelist = join('&',@{$roles});
1.922     raeburn  5274:     }
1.662     raeburn  5275:     my %personnel = ();
1.841     albertel 5276: 
                   5277:     my %servers = &get_servers($dom,'library');
                   5278:     foreach my $tryserver (keys(%servers)) {
                   5279: 	%{$personnel{$tryserver}}=();
                   5280: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5281: 					    &escape($startdate).':'.
                   5282: 					    &escape($enddate).':'.
                   5283: 					    &escape($rolelist), $tryserver))) {
                   5284: 	    my ($key,$value) = split(/\=/,$line,2);
                   5285: 	    if (($key) && ($value)) {
                   5286: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5287: 	    }
                   5288: 	}
1.662     raeburn  5289:     }
                   5290:     return %personnel;
                   5291: }
1.658     raeburn  5292: 
1.1172.2.89  raeburn  5293: sub get_active_domroles {
                   5294:     my ($dom,$roles) = @_;
                   5295:     return () unless (ref($roles) eq 'ARRAY');
                   5296:     my $now = time;
                   5297:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5298:     my %domroles;
                   5299:     foreach my $server (keys(%dompersonnel)) {
                   5300:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5301:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5302:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5303:         }
                   5304:     }
                   5305:     return %domroles;
                   5306: }
                   5307: 
1.1057    www      5308: # ----------------------------------------------------------- Interval timing 
1.149     www      5309: 
1.1153    www      5310: {
                   5311: # Caches needed for speedup of navmaps
                   5312: # We don't want to cache this for very long at all (5 seconds at most)
                   5313: # 
                   5314: # The user for whom we cache
                   5315: my $cachedkey='';
                   5316: # The cached times for this user
                   5317: my %cachedtimes=();
                   5318: # When this was last done
1.1172.2.66  raeburn  5319: my $cachedtime='';
1.1153    www      5320: 
                   5321: sub load_all_first_access {
1.1154    raeburn  5322:     my ($uname,$udom)=@_;
1.1156    www      5323:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  5324:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  5325:         return;
                   5326:     }
                   5327:     $cachedtime=time;
                   5328:     $cachedkey=$uname.':'.$udom;
                   5329:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5330: }
                   5331: 
1.504     albertel 5332: sub get_first_access {
1.1162    raeburn  5333:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 5334:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5335:     if ($argsymb) { $symb=$argsymb; }
                   5336:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5337:     if ($argmap) { $map = $argmap; }
1.926     albertel 5338:     if ($type eq 'course') {
                   5339: 	$res='course';
                   5340:     } elsif ($type eq 'map') {
1.588     albertel 5341: 	$res=&symbread($map);
                   5342:     } else {
                   5343: 	$res=$symb;
                   5344:     }
1.1153    www      5345:     &load_all_first_access($uname,$udom);
                   5346:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5347: }
                   5348: 
                   5349: sub set_first_access {
1.1162    raeburn  5350:     my ($type,$interval)=@_;
1.790     albertel 5351:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5352:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5353:     if ($type eq 'course') {
                   5354: 	$res='course';
                   5355:     } elsif ($type eq 'map') {
1.588     albertel 5356: 	$res=&symbread($map);
                   5357:     } else {
                   5358: 	$res=$symb;
                   5359:     }
1.1153    www      5360:     $cachedkey='';
1.1162    raeburn  5361:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5362:     if ($firstaccess) {
                   5363:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5364:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5365:                  "in $courseid");
                   5366:         return 'already_set';
                   5367:     } else {
1.1162    raeburn  5368:         my $start = time;
                   5369: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5370:                           $udom,$uname);
                   5371:         if ($putres eq 'ok') {
                   5372:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5373:                  $udom,$uname); 
                   5374:             &appenv(
                   5375:                      {
                   5376:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5377:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5378:                      }
                   5379:                   );
1.1172.2.97  raeburn  5380:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5381:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5382:             }
1.1172.2.102  raeburn  5383:         } elsif ($putres ne 'refused') {
                   5384:             &logthis("Result: $putres when attempting to set first access time ".
                   5385:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5386:         }
                   5387:         return $putres;
1.505     albertel 5388:     }
                   5389:     return 'already_set';
1.504     albertel 5390: }
1.1153    www      5391: }
1.1172.2.32  raeburn  5392: 
                   5393: sub checkout {
                   5394:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5395:     my $now=time;
                   5396:     my $lonhost=$perlvar{'lonHostID'};
                   5397:     my $infostr=&escape(
                   5398:                  'CHECKOUTTOKEN&'.
                   5399:                  $tuname.'&'.
                   5400:                  $tudom.'&'.
                   5401:                  $tcrsid.'&'.
                   5402:                  $symb.'&'.
                   5403:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5404:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5405:     if ($token=~/^error\:/) {
                   5406:         &logthis("<font color=\"blue\">WARNING: ".
                   5407:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5408:                  "</font>");
                   5409:         return '';
                   5410:     }
                   5411: 
                   5412:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5413:     $token=~tr/a-z/A-Z/;
                   5414: 
                   5415:     my %infohash=('resource.0.outtoken' => $token,
                   5416:                   'resource.0.checkouttime' => $now,
                   5417:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5418: 
                   5419:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5420:        return '';
                   5421:     } else {
                   5422:         &logthis("<font color=\"blue\">WARNING: ".
                   5423:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5424:                  "</font>");
                   5425:     }
                   5426: 
                   5427:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5428:                          &escape('Checkout '.$infostr.' - '.
                   5429:                                                  $token)) ne 'ok') {
                   5430:         return '';
                   5431:     } else {
                   5432:         &logthis("<font color=\"blue\">WARNING: ".
                   5433:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5434:                  "</font>");
                   5435:     }
                   5436:     return $token;
                   5437: }
                   5438: 
                   5439: # ------------------------------------------------------------ Check in an item
                   5440: 
                   5441: sub checkin {
                   5442:     my $token=shift;
                   5443:     my $now=time;
                   5444:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5445:     $lonhost=~tr/A-Z/a-z/;
                   5446:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5447:     $dtoken=~s/\W/\_/g;
                   5448:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5449:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5450: 
                   5451:     unless (($tuname) && ($tudom)) {
                   5452:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5453:         return '';
                   5454:     }
                   5455: 
                   5456:     unless (&allowed('mgr',$tcrsid)) {
                   5457:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5458:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5459:         return '';
                   5460:     }
                   5461: 
                   5462:     my %infohash=('resource.0.intoken' => $token,
                   5463:                   'resource.0.checkintime' => $now,
                   5464:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5465: 
                   5466:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5467:        return '';
                   5468:     }
                   5469: 
                   5470:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5471:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5472:         return '';
                   5473:     }
                   5474: 
                   5475:     return ($symb,$tuname,$tudom,$tcrsid);
                   5476: }
                   5477: 
1.110     www      5478: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5479: 
                   5480: sub expirespread {
                   5481:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5482:     my $cid=$env{'request.course.id'}; 
1.110     www      5483:     if ($cid) {
                   5484:        my $now=time;
                   5485:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5486:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5487:                             $env{'course.'.$cid.'.num'}.
1.110     www      5488: 	        	    ':nohist_expirationdates:'.
                   5489:                             &escape($key).'='.$now,
1.620     albertel 5490:                             $env{'course.'.$cid.'.home'})
1.110     www      5491:     }
                   5492:     return 'ok';
1.14      www      5493: }
                   5494: 
1.109     www      5495: # ----------------------------------------------------- Devalidate Spreadsheets
                   5496: 
                   5497: sub devalidate {
1.325     www      5498:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5499:     my $cid=$env{'request.course.id'}; 
1.109     www      5500:     if ($cid) {
1.391     matthew  5501:         # delete the stored spreadsheets for
                   5502:         # - the student level sheet of this user in course's homespace
                   5503:         # - the assessment level sheet for this resource 
                   5504:         #   for this user in user's homespace
1.553     albertel 5505: 	# - current conditional state info
1.325     www      5506: 	my $key=$uname.':'.$udom.':';
1.109     www      5507:         my $status=
1.299     matthew  5508: 	    &del('nohist_calculatedsheets',
1.391     matthew  5509: 		 [$key.'studentcalc:'],
1.620     albertel 5510: 		 $env{'course.'.$cid.'.domain'},
                   5511: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5512: 		.' '.
                   5513: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5514: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5515:         unless ($status eq 'ok ok') {
                   5516:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5517:                     $uname.' at '.$udom.' for '.
1.109     www      5518: 		    $symb.': '.$status);
1.133     albertel 5519:         }
1.553     albertel 5520: 	&delenv('user.state.'.$cid);
1.109     www      5521:     }
                   5522: }
                   5523: 
1.265     albertel 5524: sub get_scalar {
                   5525:     my ($string,$end) = @_;
                   5526:     my $value;
                   5527:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5528: 	$value = $1;
                   5529:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5530: 	$value = $1;
                   5531:     }
                   5532:     return &unescape($value);
                   5533: }
                   5534: 
                   5535: sub array2str {
                   5536:   my (@array) = @_;
                   5537:   my $result=&arrayref2str(\@array);
                   5538:   $result=~s/^__ARRAY_REF__//;
                   5539:   $result=~s/__END_ARRAY_REF__$//;
                   5540:   return $result;
                   5541: }
                   5542: 
1.204     albertel 5543: sub arrayref2str {
                   5544:   my ($arrayref) = @_;
1.265     albertel 5545:   my $result='__ARRAY_REF__';
1.204     albertel 5546:   foreach my $elem (@$arrayref) {
1.265     albertel 5547:     if(ref($elem) eq 'ARRAY') {
                   5548:       $result.=&arrayref2str($elem).'&';
                   5549:     } elsif(ref($elem) eq 'HASH') {
                   5550:       $result.=&hashref2str($elem).'&';
                   5551:     } elsif(ref($elem)) {
                   5552:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5553:     } else {
                   5554:       $result.=&escape($elem).'&';
                   5555:     }
                   5556:   }
                   5557:   $result=~s/\&$//;
1.265     albertel 5558:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5559:   return $result;
                   5560: }
                   5561: 
1.168     albertel 5562: sub hash2str {
1.204     albertel 5563:   my (%hash) = @_;
                   5564:   my $result=&hashref2str(\%hash);
1.265     albertel 5565:   $result=~s/^__HASH_REF__//;
                   5566:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5567:   return $result;
                   5568: }
                   5569: 
                   5570: sub hashref2str {
                   5571:   my ($hashref)=@_;
1.265     albertel 5572:   my $result='__HASH_REF__';
1.800     albertel 5573:   foreach my $key (sort(keys(%$hashref))) {
                   5574:     if (ref($key) eq 'ARRAY') {
                   5575:       $result.=&arrayref2str($key).'=';
                   5576:     } elsif (ref($key) eq 'HASH') {
                   5577:       $result.=&hashref2str($key).'=';
                   5578:     } elsif (ref($key)) {
1.265     albertel 5579:       $result.='=';
1.800     albertel 5580:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5581:     } else {
1.1132    raeburn  5582: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5583:     }
                   5584: 
1.800     albertel 5585:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5586:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5587:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5588:       $result.=&hashref2str($hashref->{$key}).'&';
                   5589:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5590:        $result.='&';
1.800     albertel 5591:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5592:     } else {
1.800     albertel 5593:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5594:     }
                   5595:   }
1.168     albertel 5596:   $result=~s/\&$//;
1.265     albertel 5597:   $result .= '__END_HASH_REF__';
1.168     albertel 5598:   return $result;
                   5599: }
                   5600: 
                   5601: sub str2hash {
1.265     albertel 5602:     my ($string)=@_;
                   5603:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5604:     return %$hash;
                   5605: }
                   5606: 
                   5607: sub str2hashref {
1.168     albertel 5608:   my ($string) = @_;
1.265     albertel 5609: 
                   5610:   my %hash;
                   5611: 
                   5612:   if($string !~ /^__HASH_REF__/) {
                   5613:       if (! ($string eq '' || !defined($string))) {
                   5614: 	  $hash{'error'}='Not hash reference';
                   5615:       }
                   5616:       return (\%hash, $string);
                   5617:   }
                   5618: 
                   5619:   $string =~ s/^__HASH_REF__//;
                   5620: 
                   5621:   while($string !~ /^__END_HASH_REF__/) {
                   5622:       #key
                   5623:       my $key='';
                   5624:       if($string =~ /^__HASH_REF__/) {
                   5625:           ($key, $string)=&str2hashref($string);
                   5626:           if(defined($key->{'error'})) {
                   5627:               $hash{'error'}='Bad data';
                   5628:               return (\%hash, $string);
                   5629:           }
                   5630:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5631:           ($key, $string)=&str2arrayref($string);
                   5632:           if($key->[0] eq 'Array reference error') {
                   5633:               $hash{'error'}='Bad data';
                   5634:               return (\%hash, $string);
                   5635:           }
                   5636:       } else {
                   5637:           $string =~ s/^(.*?)=//;
1.267     albertel 5638: 	  $key=&unescape($1);
1.265     albertel 5639:       }
                   5640:       $string =~ s/^=//;
                   5641: 
                   5642:       #value
                   5643:       my $value='';
                   5644:       if($string =~ /^__HASH_REF__/) {
                   5645:           ($value, $string)=&str2hashref($string);
                   5646:           if(defined($value->{'error'})) {
                   5647:               $hash{'error'}='Bad data';
                   5648:               return (\%hash, $string);
                   5649:           }
                   5650:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5651:           ($value, $string)=&str2arrayref($string);
                   5652:           if($value->[0] eq 'Array reference error') {
                   5653:               $hash{'error'}='Bad data';
                   5654:               return (\%hash, $string);
                   5655:           }
                   5656:       } else {
                   5657: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5658:       }
                   5659:       $string =~ s/^&//;
                   5660: 
                   5661:       $hash{$key}=$value;
1.204     albertel 5662:   }
1.265     albertel 5663: 
                   5664:   $string =~ s/^__END_HASH_REF__//;
                   5665: 
                   5666:   return (\%hash, $string);
1.204     albertel 5667: }
                   5668: 
                   5669: sub str2array {
1.265     albertel 5670:     my ($string)=@_;
                   5671:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5672:     return @$array;
                   5673: }
                   5674: 
                   5675: sub str2arrayref {
1.204     albertel 5676:   my ($string) = @_;
1.265     albertel 5677:   my @array;
                   5678: 
                   5679:   if($string !~ /^__ARRAY_REF__/) {
                   5680:       if (! ($string eq '' || !defined($string))) {
                   5681: 	  $array[0]='Array reference error';
                   5682:       }
                   5683:       return (\@array, $string);
                   5684:   }
                   5685: 
                   5686:   $string =~ s/^__ARRAY_REF__//;
                   5687: 
                   5688:   while($string !~ /^__END_ARRAY_REF__/) {
                   5689:       my $value='';
                   5690:       if($string =~ /^__HASH_REF__/) {
                   5691:           ($value, $string)=&str2hashref($string);
                   5692:           if(defined($value->{'error'})) {
                   5693:               $array[0] ='Array reference error';
                   5694:               return (\@array, $string);
                   5695:           }
                   5696:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5697:           ($value, $string)=&str2arrayref($string);
                   5698:           if($value->[0] eq 'Array reference error') {
                   5699:               $array[0] ='Array reference error';
                   5700:               return (\@array, $string);
                   5701:           }
                   5702:       } else {
                   5703: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5704:       }
                   5705:       $string =~ s/^&//;
                   5706: 
                   5707:       push(@array, $value);
1.191     harris41 5708:   }
1.265     albertel 5709: 
                   5710:   $string =~ s/^__END_ARRAY_REF__//;
                   5711: 
                   5712:   return (\@array, $string);
1.168     albertel 5713: }
                   5714: 
1.167     albertel 5715: # -------------------------------------------------------------------Temp Store
                   5716: 
1.168     albertel 5717: sub tmpreset {
                   5718:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5719:   if (!$symb) {
                   5720:     $symb=&symbread();
1.620     albertel 5721:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5722:   }
                   5723:   $symb=escape($symb);
                   5724: 
1.620     albertel 5725:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5726:   $namespace=~s/\//\_/g;
                   5727:   $namespace=~s/\W//g;
                   5728: 
1.620     albertel 5729:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5730:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5731:   if ($domain eq 'public' && $stuname eq 'public') {
                   5732:       $stuname=$ENV{'REMOTE_ADDR'};
                   5733:   }
1.1117    foxr     5734:   my $path=LONCAPA::tempdir();
1.168     albertel 5735:   my %hash;
                   5736:   if (tie(%hash,'GDBM_File',
                   5737: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5738: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5739:     foreach my $key (keys(%hash)) {
1.180     albertel 5740:       if ($key=~ /:$symb/) {
1.168     albertel 5741: 	delete($hash{$key});
                   5742:       }
                   5743:     }
                   5744:   }
                   5745: }
                   5746: 
1.167     albertel 5747: sub tmpstore {
1.168     albertel 5748:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5749: 
                   5750:   if (!$symb) {
                   5751:     $symb=&symbread();
1.620     albertel 5752:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5753:   }
                   5754:   $symb=escape($symb);
                   5755: 
                   5756:   if (!$namespace) {
                   5757:     # I don't think we would ever want to store this for a course.
                   5758:     # it seems this will only be used if we don't have a course.
1.620     albertel 5759:     #$namespace=$env{'request.course.id'};
1.168     albertel 5760:     #if (!$namespace) {
1.620     albertel 5761:       $namespace=$env{'request.state'};
1.168     albertel 5762:     #}
                   5763:   }
                   5764:   $namespace=~s/\//\_/g;
                   5765:   $namespace=~s/\W//g;
1.620     albertel 5766:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5767:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5768:   if ($domain eq 'public' && $stuname eq 'public') {
                   5769:       $stuname=$ENV{'REMOTE_ADDR'};
                   5770:   }
1.168     albertel 5771:   my $now=time;
                   5772:   my %hash;
1.1117    foxr     5773:   my $path=LONCAPA::tempdir();
1.168     albertel 5774:   if (tie(%hash,'GDBM_File',
                   5775: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5776: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5777:     $hash{"version:$symb"}++;
                   5778:     my $version=$hash{"version:$symb"};
                   5779:     my $allkeys=''; 
                   5780:     foreach my $key (keys(%$storehash)) {
                   5781:       $allkeys.=$key.':';
1.591     albertel 5782:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5783:     }
                   5784:     $hash{"$version:$symb:timestamp"}=$now;
                   5785:     $allkeys.='timestamp';
                   5786:     $hash{"$version:keys:$symb"}=$allkeys;
                   5787:     if (untie(%hash)) {
                   5788:       return 'ok';
                   5789:     } else {
                   5790:       return "error:$!";
                   5791:     }
                   5792:   } else {
                   5793:     return "error:$!";
                   5794:   }
                   5795: }
1.167     albertel 5796: 
1.168     albertel 5797: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5798: 
1.168     albertel 5799: sub tmprestore {
                   5800:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5801: 
1.168     albertel 5802:   if (!$symb) {
                   5803:     $symb=&symbread();
1.620     albertel 5804:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5805:   }
                   5806:   $symb=escape($symb);
                   5807: 
1.620     albertel 5808:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5809: 
1.620     albertel 5810:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5811:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5812:   if ($domain eq 'public' && $stuname eq 'public') {
                   5813:       $stuname=$ENV{'REMOTE_ADDR'};
                   5814:   }
1.168     albertel 5815:   my %returnhash;
                   5816:   $namespace=~s/\//\_/g;
                   5817:   $namespace=~s/\W//g;
                   5818:   my %hash;
1.1117    foxr     5819:   my $path=LONCAPA::tempdir();
1.168     albertel 5820:   if (tie(%hash,'GDBM_File',
                   5821: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5822: 	  &GDBM_READER(),0640)) {
1.168     albertel 5823:     my $version=$hash{"version:$symb"};
                   5824:     $returnhash{'version'}=$version;
                   5825:     my $scope;
                   5826:     for ($scope=1;$scope<=$version;$scope++) {
                   5827:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5828:       my @keys=split(/:/,$vkeys);
                   5829:       my $key;
                   5830:       $returnhash{"$scope:keys"}=$vkeys;
                   5831:       foreach $key (@keys) {
1.591     albertel 5832: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5833: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5834:       }
                   5835:     }
1.168     albertel 5836:     if (!(untie(%hash))) {
                   5837:       return "error:$!";
                   5838:     }
                   5839:   } else {
                   5840:     return "error:$!";
                   5841:   }
                   5842:   return %returnhash;
1.167     albertel 5843: }
                   5844: 
1.9       www      5845: # ----------------------------------------------------------------------- Store
                   5846: 
                   5847: sub store {
1.1172.2.64  raeburn  5848:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5849:     my $home='';
                   5850: 
1.168     albertel 5851:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5852: 
1.213     www      5853:     $symb=&symbclean($symb);
1.122     albertel 5854:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5855: 
1.620     albertel 5856:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5857:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5858: 
                   5859:     &devalidate($symb,$stuname,$domain);
1.109     www      5860: 
                   5861:     $symb=escape($symb);
1.187     www      5862:     if (!$namespace) { 
1.620     albertel 5863:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5864:           return ''; 
                   5865:        } 
                   5866:     }
1.620     albertel 5867:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5868: 
                   5869:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5870:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5871: 
1.12      www      5872:     my $namevalue='';
1.800     albertel 5873:     foreach my $key (keys(%$storehash)) {
                   5874:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5875:     }
1.12      www      5876:     $namevalue=~s/\&$//;
1.187     www      5877:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  5878:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5879: }
                   5880: 
1.47      www      5881: # -------------------------------------------------------------- Critical Store
                   5882: 
                   5883: sub cstore {
1.1172.2.64  raeburn  5884:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5885:     my $home='';
                   5886: 
1.168     albertel 5887:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5888: 
1.213     www      5889:     $symb=&symbclean($symb);
1.122     albertel 5890:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5891: 
1.620     albertel 5892:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5893:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5894: 
                   5895:     &devalidate($symb,$stuname,$domain);
1.109     www      5896: 
                   5897:     $symb=escape($symb);
1.187     www      5898:     if (!$namespace) { 
1.620     albertel 5899:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5900:           return ''; 
                   5901:        } 
                   5902:     }
1.620     albertel 5903:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5904: 
                   5905:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5906:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5907: 
1.47      www      5908:     my $namevalue='';
1.800     albertel 5909:     foreach my $key (keys(%$storehash)) {
                   5910:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5911:     }
1.47      www      5912:     $namevalue=~s/\&$//;
1.187     www      5913:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5914:     return critical
1.1172.2.64  raeburn  5915:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5916: }
                   5917: 
1.9       www      5918: # --------------------------------------------------------------------- Restore
                   5919: 
                   5920: sub restore {
1.124     www      5921:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5922:     my $home='';
                   5923: 
1.168     albertel 5924:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5925: 
1.122     albertel 5926:     if (!$symb) {
1.1172.2.26  raeburn  5927:         return if ($namespace eq 'courserequests');
                   5928:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5929:     } else {
1.1172.2.26  raeburn  5930:         unless ($namespace eq 'courserequests') {
                   5931:             $symb=&escape(&symbclean($symb));
                   5932:         }
1.122     albertel 5933:     }
1.188     www      5934:     if (!$namespace) { 
1.620     albertel 5935:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5936:           return ''; 
                   5937:        } 
                   5938:     }
1.620     albertel 5939:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5940:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5941:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5942:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5943: 
1.12      www      5944:     my %returnhash=();
1.800     albertel 5945:     foreach my $line (split(/\&/,$answer)) {
                   5946: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5947:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5948:     }
1.75      www      5949:     my $version;
                   5950:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5951:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5952:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5953:        }
1.75      www      5954:     }
1.13      www      5955:     return %returnhash;
1.34      www      5956: }
                   5957: 
                   5958: # ---------------------------------------------------------- Course Description
1.1118    foxr     5959: #
                   5960: #  
1.34      www      5961: 
                   5962: sub coursedescription {
1.731     albertel 5963:     my ($courseid,$args)=@_;
1.34      www      5964:     $courseid=~s/^\///;
1.49      www      5965:     $courseid=~s/\_/\//g;
1.34      www      5966:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5967:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5968:     my $normalid=$cdomain.'_'.$cnum;
                   5969:     # need to always cache even if we get errors otherwise we keep 
                   5970:     # trying and trying and trying to get the course description.
                   5971:     my %envhash=();
                   5972:     my %returnhash=();
1.731     albertel 5973:     
                   5974:     my $expiretime=600;
                   5975:     if ($env{'request.course.id'} eq $normalid) {
                   5976: 	$expiretime=120;
                   5977:     }
                   5978: 
                   5979:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5980:     if (!$args->{'freshen_cache'}
                   5981: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5982: 	foreach my $key (keys(%env)) {
                   5983: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5984: 	    my ($setting) = $1;
                   5985: 	    $returnhash{$setting} = $env{$key};
                   5986: 	}
                   5987: 	return %returnhash;
                   5988:     }
                   5989: 
1.1118    foxr     5990:     # get the data again
                   5991: 
1.731     albertel 5992:     if (!$args->{'one_time'}) {
                   5993: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5994:     }
1.811     albertel 5995: 
1.34      www      5996:     if ($chome ne 'no_host') {
1.302     albertel 5997:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5998:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5999: 	   my $username = $env{'user.name'}; # Defult username
                   6000: 	   if(defined $args->{'user'}) {
                   6001: 	       $username = $args->{'user'};
                   6002: 	   }
1.129     albertel 6003:            $returnhash{'home'}= $chome;
                   6004: 	   $returnhash{'domain'} = $cdomain;
                   6005: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6006:            if (!defined($returnhash{'type'})) {
                   6007:                $returnhash{'type'} = 'Course';
                   6008:            }
1.130     albertel 6009:            while (my ($name,$value) = each %returnhash) {
1.53      www      6010:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6011:            }
1.270     www      6012:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6013:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6014: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6015:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6016:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6017:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6018:        }
                   6019:     }
1.731     albertel 6020:     if (!$args->{'one_time'}) {
1.949     raeburn  6021: 	&appenv(\%envhash);
1.731     albertel 6022:     }
1.302     albertel 6023:     return %returnhash;
1.461     www      6024: }
                   6025: 
1.1080    raeburn  6026: sub update_released_required {
                   6027:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6028:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6029:         $cid = $env{'request.course.id'};
                   6030:         $cdom = $env{'course.'.$cid.'.domain'};
                   6031:         $cnum = $env{'course.'.$cid.'.num'};
                   6032:         $chome = $env{'course.'.$cid.'.home'};
                   6033:     }
                   6034:     if ($needsrelease) {
                   6035:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6036:         my $needsupdate;
                   6037:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6038:             $needsupdate = 1;
                   6039:         } else {
                   6040:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6041:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6042:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6043:                 $needsupdate = 1;
                   6044:             }
                   6045:         }
                   6046:         if ($needsupdate) {
                   6047:             my %needshash = (
                   6048:                              'internal.releaserequired' => $needsrelease,
                   6049:                             );
                   6050:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6051:             if ($putresult eq 'ok') {
                   6052:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6053:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6054:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6055:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6056:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6057:                 }
                   6058:             }
                   6059:         }
                   6060:     }
                   6061:     return;
                   6062: }
                   6063: 
1.461     www      6064: # -------------------------------------------------See if a user is privileged
                   6065: 
                   6066: sub privileged {
1.1172.2.23  raeburn  6067:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6068:     my $now = time;
1.1172.2.23  raeburn  6069:     my $roles;
                   6070:     if (ref($possroles) eq 'ARRAY') {
                   6071:         $roles = $possroles;
                   6072:     } else {
                   6073:         $roles = ['dc','su'];
                   6074:     }
                   6075:     if (ref($possdomains) eq 'ARRAY') {
                   6076:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6077:         foreach my $dom (@{$possdomains}) {
                   6078:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6079:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6080:                 foreach my $role (@{$roles}) {
                   6081:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6082:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6083:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6084:                             return 1 unless (($end && $end < $now) ||
                   6085:                                              ($start && $start > $now));
                   6086:                         }
                   6087:                     }
                   6088:                 }
                   6089:             }
                   6090:         }
                   6091:     } else {
                   6092:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6093:         my $now = time;
1.1170    droeschl 6094: 
1.1172.2.58  raeburn  6095:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6096:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6097:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6098:                 return 1 unless ($tend && $tend < $now)
                   6099:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6100:             }
1.1172.2.23  raeburn  6101:         }
                   6102:     }
1.461     www      6103:     return 0;
1.9       www      6104: }
1.1       albertel 6105: 
1.1172.2.23  raeburn  6106: sub privileged_by_domain {
                   6107:     my ($domains,$roles) = @_;
                   6108:     my %privileged = ();
                   6109:     my $cachetime = 60*60*24;
                   6110:     my $now = time;
                   6111:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6112:         return %privileged;
                   6113:     }
                   6114:     foreach my $dom (@{$domains}) {
                   6115:         next if (ref($privileged{$dom}) eq 'HASH');
                   6116:         my $needroles;
                   6117:         foreach my $role (@{$roles}) {
                   6118:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6119:             if (defined($cached)) {
                   6120:                 if (ref($result) eq 'HASH') {
                   6121:                     $privileged{$dom}{$role} = $result;
                   6122:                 }
                   6123:             } else {
                   6124:                 $needroles = 1;
                   6125:             }
                   6126:         }
                   6127:         if ($needroles) {
                   6128:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6129:             $privileged{$dom} = {};
                   6130:             foreach my $server (keys(%dompersonnel)) {
                   6131:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6132:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6133:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6134:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6135:                         next if ($end && $end < $now);
                   6136:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6137:                             $dompersonnel{$server}{$item};
                   6138:                     }
                   6139:                 }
                   6140:             }
                   6141:             if (ref($privileged{$dom}) eq 'HASH') {
                   6142:                 foreach my $role (@{$roles}) {
                   6143:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6144:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6145:                     } else {
                   6146:                         my %hash = ();
                   6147:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6148:                     }
                   6149:                 }
                   6150:             }
                   6151:         }
                   6152:     }
                   6153:     return %privileged;
                   6154: }
                   6155: 
1.103     harris41 6156: # -------------------------------------------------------- Get user privileges
1.11      www      6157: 
                   6158: sub rolesinit {
1.1169    droeschl 6159:     my ($domain, $username) = @_;
                   6160:     my %userroles = ('user.login.time' => time);
                   6161:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6162: 
                   6163:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6164:     # also, blocking can be triggered by an activating timer
                   6165:     # it's saved in the user's %env.
                   6166:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6167:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6168:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6169:         %timerintchk, %timerintenv);
                   6170: 
1.1162    raeburn  6171:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6172:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6173:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6174:     }
1.1169    droeschl 6175: 
1.1162    raeburn  6176:     foreach my $key (keys(%timerinterval)) {
                   6177:         my ($cid,$rest) = split(/\0/,$key);
                   6178:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6179:     }
1.1169    droeschl 6180: 
1.11      www      6181:     my %allroles=();
1.1162    raeburn  6182:     my %allgroups=();
1.11      www      6183: 
1.1172.2.58  raeburn  6184:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6185:         my $role = $rolesdump{$area};
                   6186:         $area =~ s/\_\w\w$//;
                   6187: 
                   6188:         my ($trole, $tend, $tstart, $group_privs);
                   6189: 
                   6190:         if ($role =~ /^cr/) {
                   6191:         # Custom role, defined by a user 
                   6192:         # e.g., user.role.cr/msu/smith/mynewrole
                   6193:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6194:                 $trole = $1;
                   6195:                 ($tend, $tstart) = split('_', $2);
                   6196:             } else {
                   6197:                 $trole = $role;
                   6198:             }
                   6199:         } elsif ($role =~ m|^gr/|) {
                   6200:         # Role of member in a group, defined within a course/community
                   6201:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6202:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6203:             next if $tstart eq '-1';
                   6204:             ($trole, $group_privs) = split(/\//, $trole);
                   6205:             $group_privs = &unescape($group_privs);
                   6206:         } else {
                   6207:         # Just a normal role, defined in roles.tab
                   6208:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6209:         }
                   6210: 
                   6211:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6212:                  $username);
                   6213:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6214: 
                   6215:         # role expired or not available yet?
                   6216:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6217:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6218: 
                   6219:         next if $area eq '' or $trole eq '';
                   6220: 
                   6221:         my $spec = "$trole.$area";
                   6222:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6223: 
                   6224:         if ($trole =~ /^cr\//) {
                   6225:         # Custom role, defined by a user
                   6226:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6227:         } elsif ($trole eq 'gr') {
                   6228:         # Role of a member in a group, defined within a course/community
                   6229:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6230:             next;
                   6231:         } else {
                   6232:         # Normal role, defined in roles.tab
                   6233:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6234:         }
                   6235: 
                   6236:         my $cid = $tdomain.'_'.$trest;
                   6237:         unless ($firstaccchk{$cid}) {
                   6238:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6239:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6240:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6241:                         $coursetimerstarts{$cid}{$item}; 
                   6242:                 }
                   6243:             }
                   6244:             $firstaccchk{$cid} = 1;
                   6245:         }
                   6246:         unless ($timerintchk{$cid}) {
                   6247:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6248:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6249:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6250:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6251:                 }
1.12      www      6252:             }
1.1169    droeschl 6253:             $timerintchk{$cid} = 1;
1.191     harris41 6254:         }
1.11      www      6255:     }
1.1169    droeschl 6256: 
1.1172.2.91  raeburn  6257:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6258:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6259:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6260:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6261: 
1.1162    raeburn  6262:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6263: }
                   6264: 
1.567     raeburn  6265: sub set_arearole {
1.1172.2.19  raeburn  6266:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6267:     unless ($nolog) {
1.567     raeburn  6268: # log the associated role with the area
1.1172.2.19  raeburn  6269:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6270:     }
1.743     albertel 6271:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6272: }
                   6273: 
                   6274: sub custom_roleprivs {
                   6275:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6276:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6277:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6278:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6279:         my ($rdummy,$roledef)=
                   6280:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6281:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6282:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6283:             if (defined($syspriv)) {
1.1043    raeburn  6284:                 if ($trest =~ /^$match_community$/) {
                   6285:                     $syspriv =~ s/bre\&S//; 
                   6286:                 }
1.567     raeburn  6287:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6288:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6289:             }
                   6290:             if ($tdomain ne '') {
                   6291:                 if (defined($dompriv)) {
                   6292:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6293:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6294:                 }
                   6295:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6296:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6297:                         my $rolename = $1;
                   6298:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6299:                     }
1.567     raeburn  6300:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6301:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6302:                 }
                   6303:             }
                   6304:         }
                   6305:     }
                   6306: }
                   6307: 
1.1172.2.89  raeburn  6308: sub course_adhocrole_privs {
                   6309:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6310:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6311:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6312:         my (%currprivs,%storeprivs);
                   6313:         foreach my $item (split(/:/,$coursepriv)) {
                   6314:             my ($priv,$restrict) = split(/\&/,$item);
                   6315:             $currprivs{$priv} = $restrict;
                   6316:         }
                   6317:         my (%possadd,%possremove,%full);
                   6318:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6319:             my ($priv,$restrict)=split(/\&/,$item);
                   6320:             $full{$priv} = $restrict;
                   6321:         }
                   6322:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6323:              next if ($item eq '');
                   6324:              my ($rule,$rest) = split(/=/,$item);
                   6325:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6326:              foreach my $priv (split(/:/,$rest)) {
                   6327:                  if ($priv ne '') {
                   6328:                      if ($rule eq 'off') {
                   6329:                          $possremove{$priv} = 1;
                   6330:                      } else {
                   6331:                          $possadd{$priv} = 1;
                   6332:                      }
                   6333:                  }
                   6334:              }
                   6335:          }
                   6336:          foreach my $priv (sort(keys(%full))) {
                   6337:              if (exists($currprivs{$priv})) {
                   6338:                  unless (exists($possremove{$priv})) {
                   6339:                      $storeprivs{$priv} = $currprivs{$priv};
                   6340:                  }
                   6341:              } elsif (exists($possadd{$priv})) {
                   6342:                  $storeprivs{$priv} = $full{$priv};
                   6343:              }
                   6344:          }
                   6345:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6346:      }
                   6347:      return $coursepriv;
                   6348: }
                   6349: 
1.678     raeburn  6350: sub group_roleprivs {
                   6351:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6352:     my $access = 1;
                   6353:     my $now = time;
                   6354:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6355:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6356:     if ($access) {
1.811     albertel 6357:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6358:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6359:     }
                   6360: }
1.567     raeburn  6361: 
                   6362: sub standard_roleprivs {
                   6363:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6364:     if (defined($pr{$trole.':s'})) {
                   6365:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6366:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6367:     }
                   6368:     if ($tdomain ne '') {
                   6369:         if (defined($pr{$trole.':d'})) {
                   6370:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6371:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6372:         }
                   6373:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6374:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6375:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6376:         }
                   6377:     }
                   6378: }
                   6379: 
                   6380: sub set_userprivs {
1.1064    raeburn  6381:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6382:     my $author=0;
                   6383:     my $adv=0;
1.1172.2.91  raeburn  6384:     my $rar=0;
1.678     raeburn  6385:     my %grouproles = ();
                   6386:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6387:         my @groupkeys; 
1.1000    raeburn  6388:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6389:             push(@groupkeys,$role);
                   6390:         }
                   6391:         if (ref($groups_roles) eq 'HASH') {
                   6392:             foreach my $key (keys(%{$groups_roles})) {
                   6393:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6394:                     push(@groupkeys,$key);
                   6395:                 }
                   6396:             }
                   6397:         }
                   6398:         if (@groupkeys > 0) {
                   6399:             foreach my $role (@groupkeys) {
                   6400:                 my ($trole,$area,$sec,$extendedarea);
                   6401:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6402:                     $trole = $1;
                   6403:                     $area = $2;
                   6404:                     $sec = $3;
                   6405:                     $extendedarea = $area.$sec;
                   6406:                     if (exists($$allgroups{$area})) {
                   6407:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6408:                             my $spec = $trole.'.'.$extendedarea;
                   6409:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6410:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6411:                         }
1.678     raeburn  6412:                     }
                   6413:                 }
                   6414:             }
                   6415:         }
                   6416:     }
1.800     albertel 6417:     foreach my $group (keys(%grouproles)) {
                   6418:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6419:     }
1.800     albertel 6420:     foreach my $role (keys(%{$allroles})) {
                   6421:         my %thesepriv;
1.941     raeburn  6422:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6423:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6424:             if ($item ne '') {
                   6425:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6426:                 if ($restrictions eq '') {
                   6427:                     $thesepriv{$privilege}='F';
                   6428:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6429:                     $thesepriv{$privilege}.=$restrictions;
                   6430:                 }
                   6431:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6432:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6433:             }
                   6434:         }
                   6435:         my $thesestr='';
1.1104    raeburn  6436:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6437: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6438: 	}
                   6439:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6440:     }
1.1172.2.91  raeburn  6441:     return ($author,$adv,$rar);
1.567     raeburn  6442: }
                   6443: 
1.994     raeburn  6444: sub role_status {
1.1104    raeburn  6445:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6446:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6447:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6448:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6449:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6450:             $$where = '/'.$two;
1.994     raeburn  6451:             $$trolecode=$$role.'.'.$$where;
                   6452:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6453:             $$tstatus='is';
1.1104    raeburn  6454:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6455:                 $$tstatus='future';
1.1034    raeburn  6456:                 if ($$tstart<$now) {
                   6457:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6458:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6459:                             my (%allroles,%allgroups,$group_privs,
                   6460:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6461:                             my %userroles = (
                   6462:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6463:                             );
1.1064    raeburn  6464:                             @rolecodes = ('cm'); 
1.1002    raeburn  6465:                             my $spec=$$role.'.'.$$where;
                   6466:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6467:                             if ($$role =~ /^cr\//) {
                   6468:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6469:                                 push(@rolecodes,'cr');
1.1002    raeburn  6470:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6471:                                 push(@rolecodes,$$role);
1.1002    raeburn  6472:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6473:                                                     $env{'user.name'});
1.1064    raeburn  6474:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6475:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6476:                                 $group_privs = &unescape($group_privs);
                   6477:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6478:                                 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  6479:                                 &get_groups_roles($tdomain,$trest,
                   6480:                                                   \%course_roles,\@rolecodes,
                   6481:                                                   \%groups_roles);
1.1002    raeburn  6482:                             } else {
1.1064    raeburn  6483:                                 push(@rolecodes,$$role);
1.1002    raeburn  6484:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6485:                             }
1.1172.2.91  raeburn  6486:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6487:                                                                    \%groups_roles);
1.1064    raeburn  6488:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6489:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6490:                         }
                   6491:                     }
1.1034    raeburn  6492:                     $$tstatus = 'is';
1.1002    raeburn  6493:                 }
1.994     raeburn  6494:             }
                   6495:             if ($$tend) {
1.1104    raeburn  6496:                 if ($$tend<$update) {
1.994     raeburn  6497:                     $$tstatus='expired';
                   6498:                 } elsif ($$tend<$now) {
                   6499:                     $$tstatus='will_not';
                   6500:                 }
                   6501:             }
                   6502:         }
                   6503:     }
                   6504: }
                   6505: 
1.1104    raeburn  6506: sub get_groups_roles {
                   6507:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6508:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6509:                   (ref($rolecodes) eq 'ARRAY') && 
                   6510:                   (ref($groups_roles) eq 'HASH')); 
                   6511:     if (keys(%{$cdom_courseroles}) > 0) {
                   6512:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6513:         if ($cdom ne '' && $cnum ne '') {
                   6514:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6515:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6516:                     my $crsrole = $1;
                   6517:                     my $crssec = $2;
                   6518:                     if ($crsrole =~ /^cr/) {
                   6519:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6520:                             push(@{$rolecodes},'cr');
                   6521:                         }
                   6522:                     } else {
                   6523:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6524:                             push(@{$rolecodes},$crsrole);
                   6525:                         }
                   6526:                     }
                   6527:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6528:                     if ($crssec ne '') {
                   6529:                         $rolekey .= "/$crssec";
                   6530:                     }
                   6531:                     $rolekey .= './';
                   6532:                     $groups_roles->{$rolekey} = $rolecodes;
                   6533:                 }
                   6534:             }
                   6535:         }
                   6536:     }
                   6537:     return;
                   6538: }
                   6539: 
                   6540: sub delete_env_groupprivs {
                   6541:     my ($where,$courseroles,$possroles) = @_;
                   6542:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6543:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6544:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6545:         %{$courseroles->{$udom}} =
                   6546:             &get_my_roles('','','userroles',['active'],
                   6547:                           $possroles,[$udom],1);
                   6548:     }
                   6549:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6550:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6551:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6552:             my $area = '/'.$cdom.'/'.$cnum;
                   6553:             my $privkey = "user.priv.$crsrole.$area";
                   6554:             if ($crssec ne '') {
                   6555:                 $privkey .= '/'.$crssec;
                   6556:             }
                   6557:             $privkey .= ".$area/$group";
                   6558:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6559:         }
                   6560:     }
                   6561:     return;
                   6562: }
                   6563: 
1.994     raeburn  6564: sub check_adhoc_privs {
1.1172.2.86  raeburn  6565:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6566:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6567:     if ($sec) {
                   6568:         $cckey .= '/'.$sec;
                   6569:     }
1.1172.2.9  raeburn  6570:     my $setprivs;
1.994     raeburn  6571:     if ($env{$cckey}) {
                   6572:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6573:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6574:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6575:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6576:             $setprivs = 1;
1.994     raeburn  6577:         }
                   6578:     } else {
1.1172.2.87  raeburn  6579:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6580:         $setprivs = 1;
1.994     raeburn  6581:     }
1.1172.2.9  raeburn  6582:     return $setprivs;
1.994     raeburn  6583: }
                   6584: 
                   6585: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6586: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6587:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6588:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6589:     if ($sec ne '') {
                   6590:         $area .= '/'.$sec;
                   6591:     }
1.994     raeburn  6592:     my $spec = $role.'.'.$area;
                   6593:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6594:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6595:     my %rolehash = ();
1.1172.2.89  raeburn  6596:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6597:         my $rolename = $1;
1.1172.2.84  raeburn  6598:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6599:         my %domdef = &get_domain_defaults($dcdom);
                   6600:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6601:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6602:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6603:             }
                   6604:         }
1.1172.2.84  raeburn  6605:     } else {
                   6606:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6607:     }
1.1172.2.91  raeburn  6608:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6609:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6610:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6611:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6612:         &appenv( {'request.role'        => $spec,
                   6613:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6614:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6615:                  }
                   6616:                );
                   6617:         my $tadv=0;
                   6618:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6619:         &appenv({'request.role.adv'    => $tadv});
                   6620:     }
1.994     raeburn  6621: }
                   6622: 
1.12      www      6623: # --------------------------------------------------------------- get interface
                   6624: 
                   6625: sub get {
1.131     albertel 6626:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6627:    my $items='';
1.800     albertel 6628:    foreach my $item (@$storearr) {
                   6629:        $items.=&escape($item).'&';
1.191     harris41 6630:    }
1.12      www      6631:    $items=~s/\&$//;
1.620     albertel 6632:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6633:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6634:    my $uhome=&homeserver($uname,$udomain);
                   6635: 
1.133     albertel 6636:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6637:    my @pairs=split(/\&/,$rep);
1.273     albertel 6638:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6639:      return @pairs;
                   6640:    }
1.15      www      6641:    my %returnhash=();
1.42      www      6642:    my $i=0;
1.800     albertel 6643:    foreach my $item (@$storearr) {
                   6644:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6645:       $i++;
1.191     harris41 6646:    }
1.15      www      6647:    return %returnhash;
1.27      www      6648: }
                   6649: 
                   6650: # --------------------------------------------------------------- del interface
                   6651: 
                   6652: sub del {
1.133     albertel 6653:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6654:    my $items='';
1.800     albertel 6655:    foreach my $item (@$storearr) {
                   6656:        $items.=&escape($item).'&';
1.191     harris41 6657:    }
1.984     neumanie 6658: 
1.27      www      6659:    $items=~s/\&$//;
1.620     albertel 6660:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6661:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6662:    my $uhome=&homeserver($uname,$udomain);
                   6663:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6664: }
                   6665: 
                   6666: # -------------------------------------------------------------- dump interface
                   6667: 
1.1172.2.22  raeburn  6668: sub unserialize {
                   6669:     my ($rep, $escapedkeys) = @_;
                   6670: 
                   6671:     return {} if $rep =~ /^error/;
                   6672: 
                   6673:     my %returnhash=();
                   6674:     foreach my $item (split(/\&/,$rep)) {
                   6675:         my ($key, $value) = split(/=/, $item, 2);
                   6676:         $key = unescape($key) unless $escapedkeys;
                   6677:         next if $key =~ /^error: 2 /;
                   6678:         $returnhash{$key} = &thaw_unescape($value);
                   6679:     }
                   6680:     return \%returnhash;
                   6681: }
                   6682: 
                   6683: # see Lond::dump_with_regexp
                   6684: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6685: sub dump {
1.1172.2.22  raeburn  6686:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6687:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6688:     if (!$uname) { $uname=$env{'user.name'}; }
                   6689:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6690: 
1.1172.2.55  raeburn  6691:     if ($regexp) {
                   6692:         $regexp=&escape($regexp);
                   6693:     } else {
                   6694:         $regexp='.';
                   6695:     }
1.1172.2.22  raeburn  6696:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6697:         # user is hosted on this machine
1.1172.2.55  raeburn  6698:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6699:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6700:         return %{&unserialize($reply, $escapedkeys)};
                   6701:     }
1.1166    raeburn  6702:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6703:     my @pairs=split(/\&/,$rep);
                   6704:     my %returnhash=();
1.1098    foxr     6705:     if (!($rep =~ /^error/ )) {
                   6706: 	foreach my $item (@pairs) {
                   6707: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6708:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6709: 	    next if ($key =~ /^error: 2 /);
                   6710: 	    $returnhash{$key}=&thaw_unescape($value);
                   6711: 	}
1.755     albertel 6712:     }
                   6713:     return %returnhash;
1.407     www      6714: }
                   6715: 
1.1098    foxr     6716: 
1.717     albertel 6717: # --------------------------------------------------------- dumpstore interface
                   6718: 
                   6719: sub dumpstore {
                   6720:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6721:    # same as dump but keys must be escaped. They may contain colon separated
                   6722:    # lists of values that may themself contain colons (e.g. symbs).
                   6723:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6724: }
                   6725: 
1.407     www      6726: # -------------------------------------------------------------- keys interface
                   6727: 
                   6728: sub getkeys {
                   6729:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6730:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6731:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6732:    my $uhome=&homeserver($uname,$udomain);
                   6733:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6734:    my @keyarray=();
1.800     albertel 6735:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6736:       next if ($key =~ /^error: 2 /);
1.800     albertel 6737:       push(@keyarray,&unescape($key));
1.407     www      6738:    }
                   6739:    return @keyarray;
1.318     matthew  6740: }
                   6741: 
1.319     matthew  6742: # --------------------------------------------------------------- currentdump
                   6743: sub currentdump {
1.328     matthew  6744:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6745:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6746:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6747:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6748:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6749:    my $rep;
                   6750: 
                   6751:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6752:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6753:                    $courseid)));
                   6754:    } else {
                   6755:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6756:    }
                   6757: 
1.318     matthew  6758:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6759:    #
1.318     matthew  6760:    my %returnhash=();
1.319     matthew  6761:    #
                   6762:    if ($rep eq "unknown_cmd") { 
                   6763:        # an old lond will not know currentdump
                   6764:        # Do a dump and make it look like a currentdump
1.822     albertel 6765:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6766:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6767:        my %hash = @tmp;
                   6768:        @tmp=();
1.424     matthew  6769:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6770:    } else {
                   6771:        my @pairs=split(/\&/,$rep);
1.800     albertel 6772:        foreach my $pair (@pairs) {
                   6773:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6774:            my ($symb,$param) = split(/:/,$key);
                   6775:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6776:                                                         &thaw_unescape($value);
1.319     matthew  6777:        }
1.191     harris41 6778:    }
1.12      www      6779:    return %returnhash;
1.424     matthew  6780: }
                   6781: 
                   6782: sub convert_dump_to_currentdump{
                   6783:     my %hash = %{shift()};
                   6784:     my %returnhash;
                   6785:     # Code ripped from lond, essentially.  The only difference
                   6786:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6787:     # we might run in to problems with parameter names =~ /^v\./
                   6788:     while (my ($key,$value) = each(%hash)) {
                   6789:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6790: 	$symb  = &unescape($symb);
                   6791: 	$param = &unescape($param);
1.424     matthew  6792:         next if ($v eq 'version' || $symb eq 'keys');
                   6793:         next if (exists($returnhash{$symb}) &&
                   6794:                  exists($returnhash{$symb}->{$param}) &&
                   6795:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6796:         $returnhash{$symb}->{$param}=$value;
                   6797:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6798:     }
                   6799:     #
                   6800:     # Remove all of the keys in the hashes which keep track of
                   6801:     # the version of the parameter.
                   6802:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6803:         # use a foreach because we are going to delete from the hash.
                   6804:         foreach my $key (keys(%$param_hash)) {
                   6805:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6806:         }
                   6807:     }
                   6808:     return \%returnhash;
1.12      www      6809: }
                   6810: 
1.627     albertel 6811: # ------------------------------------------------------ critical inc interface
                   6812: 
                   6813: sub cinc {
                   6814:     return &inc(@_,'critical');
                   6815: }
                   6816: 
1.449     matthew  6817: # --------------------------------------------------------------- inc interface
                   6818: 
                   6819: sub inc {
1.627     albertel 6820:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6821:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6822:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6823:     my $uhome=&homeserver($uname,$udomain);
                   6824:     my $items='';
                   6825:     if (! ref($store)) {
                   6826:         # got a single value, so use that instead
                   6827:         $items = &escape($store).'=&';
                   6828:     } elsif (ref($store) eq 'SCALAR') {
                   6829:         $items = &escape($$store).'=&';        
                   6830:     } elsif (ref($store) eq 'ARRAY') {
                   6831:         $items = join('=&',map {&escape($_);} @{$store});
                   6832:     } elsif (ref($store) eq 'HASH') {
                   6833:         while (my($key,$value) = each(%{$store})) {
                   6834:             $items.= &escape($key).'='.&escape($value).'&';
                   6835:         }
                   6836:     }
                   6837:     $items=~s/\&$//;
1.627     albertel 6838:     if ($critical) {
                   6839: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6840:     } else {
                   6841: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6842:     }
1.449     matthew  6843: }
                   6844: 
1.12      www      6845: # --------------------------------------------------------------- put interface
                   6846: 
                   6847: sub put {
1.134     albertel 6848:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6850:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6851:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6852:    my $items='';
1.800     albertel 6853:    foreach my $item (keys(%$storehash)) {
                   6854:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6855:    }
1.12      www      6856:    $items=~s/\&$//;
1.134     albertel 6857:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6858: }
                   6859: 
1.631     albertel 6860: # ------------------------------------------------------------ newput interface
                   6861: 
                   6862: sub newput {
                   6863:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6865:    if (!$uname) { $uname=$env{'user.name'}; }
                   6866:    my $uhome=&homeserver($uname,$udomain);
                   6867:    my $items='';
                   6868:    foreach my $key (keys(%$storehash)) {
                   6869:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6870:    }
                   6871:    $items=~s/\&$//;
                   6872:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6873: }
                   6874: 
                   6875: # ---------------------------------------------------------  putstore interface
                   6876: 
1.524     raeburn  6877: sub putstore {
1.1172.2.59  raeburn  6878:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6879:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6880:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6881:    my $uhome=&homeserver($uname,$udomain);
                   6882:    my $items='';
1.715     albertel 6883:    foreach my $key (keys(%$storehash)) {
                   6884:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6885:    }
1.715     albertel 6886:    $items=~s/\&$//;
1.716     albertel 6887:    my $esc_symb=&escape($symb);
                   6888:    my $esc_v=&escape($version);
1.715     albertel 6889:    my $reply =
1.716     albertel 6890:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6891: 	      $uhome);
1.1172.2.59  raeburn  6892:    if (($tolog) && ($reply eq 'ok')) {
                   6893:        my $namevalue='';
                   6894:        foreach my $key (keys(%{$storehash})) {
                   6895:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6896:        }
                   6897:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6898:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6899:                      '&version='.$esc_v.
                   6900:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6901:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6902:    }
1.715     albertel 6903:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6904:        # gfall back to way things use to be done
1.715     albertel 6905:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6906: 			    $uname);
1.524     raeburn  6907:    }
1.715     albertel 6908:    return $reply;
                   6909: }
                   6910: 
                   6911: sub old_putstore {
1.716     albertel 6912:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6913:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6914:     if (!$uname) { $uname=$env{'user.name'}; }
                   6915:     my $uhome=&homeserver($uname,$udomain);
                   6916:     my %newstorehash;
1.800     albertel 6917:     foreach my $item (keys(%$storehash)) {
                   6918: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6919: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6920:     }
                   6921:     my $items='';
                   6922:     my %allitems = ();
1.800     albertel 6923:     foreach my $item (keys(%newstorehash)) {
                   6924: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6925: 	    my $key = $1.':keys:'.$2;
                   6926: 	    $allitems{$key} .= $3.':';
                   6927: 	}
1.800     albertel 6928: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6929:     }
1.800     albertel 6930:     foreach my $item (keys(%allitems)) {
                   6931: 	$allitems{$item} =~ s/\:$//;
                   6932: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6933:     }
                   6934:     $items=~s/\&$//;
                   6935:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6936: }
                   6937: 
1.47      www      6938: # ------------------------------------------------------ critical put interface
                   6939: 
                   6940: sub cput {
1.134     albertel 6941:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6942:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6943:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6944:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6945:    my $items='';
1.800     albertel 6946:    foreach my $item (keys(%$storehash)) {
                   6947:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6948:    }
1.47      www      6949:    $items=~s/\&$//;
1.134     albertel 6950:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6951: }
                   6952: 
                   6953: # -------------------------------------------------------------- eget interface
                   6954: 
                   6955: sub eget {
1.133     albertel 6956:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6957:    my $items='';
1.800     albertel 6958:    foreach my $item (@$storearr) {
                   6959:        $items.=&escape($item).'&';
1.191     harris41 6960:    }
1.12      www      6961:    $items=~s/\&$//;
1.620     albertel 6962:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6963:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6964:    my $uhome=&homeserver($uname,$udomain);
                   6965:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6966:    my @pairs=split(/\&/,$rep);
                   6967:    my %returnhash=();
1.42      www      6968:    my $i=0;
1.800     albertel 6969:    foreach my $item (@$storearr) {
                   6970:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6971:       $i++;
1.191     harris41 6972:    }
1.12      www      6973:    return %returnhash;
                   6974: }
                   6975: 
1.667     albertel 6976: # ------------------------------------------------------------ tmpput interface
                   6977: sub tmpput {
1.802     raeburn  6978:     my ($storehash,$server,$context)=@_;
1.667     albertel 6979:     my $items='';
1.800     albertel 6980:     foreach my $item (keys(%$storehash)) {
                   6981: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6982:     }
                   6983:     $items=~s/\&$//;
1.802     raeburn  6984:     if (defined($context)) {
                   6985:         $items .= ':'.&escape($context);
                   6986:     }
1.667     albertel 6987:     return &reply("tmpput:$items",$server);
                   6988: }
                   6989: 
                   6990: # ------------------------------------------------------------ tmpget interface
                   6991: sub tmpget {
1.688     albertel 6992:     my ($token,$server)=@_;
                   6993:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6994:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6995:     my %returnhash;
1.1172.2.85  raeburn  6996:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6997:         return %returnhash;
                   6998:     }
1.667     albertel 6999:     foreach my $item (split(/\&/,$rep)) {
                   7000: 	my ($key,$value)=split(/=/,$item);
                   7001: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7002:     }
                   7003:     return %returnhash;
                   7004: }
                   7005: 
1.1113    raeburn  7006: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7007: sub tmpdel {
                   7008:     my ($token,$server)=@_;
                   7009:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7010:     return &reply("tmpdel:$token",$server);
                   7011: }
                   7012: 
1.1172.2.13  raeburn  7013: # ------------------------------------------------------------ get_timebased_id
                   7014: 
                   7015: sub get_timebased_id {
                   7016:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7017:         $maxtries) = @_;
                   7018:     my ($newid,$error,$dellock);
                   7019:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7020:         return ('','ok','invalid call to get suffix');
                   7021:     }
                   7022: 
                   7023: # set defaults for any optional args for which values were not supplied
                   7024:     if ($who eq '') {
                   7025:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7026:     }
                   7027:     if (!$locktries) {
                   7028:         $locktries = 3;
                   7029:     }
                   7030:     if (!$maxtries) {
                   7031:         $maxtries = 10;
                   7032:     }
                   7033: 
                   7034:     if (($cdom eq '') || ($cnum eq '')) {
                   7035:         if ($env{'request.course.id'}) {
                   7036:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7037:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7038:         }
                   7039:         if (($cdom eq '') || ($cnum eq '')) {
                   7040:             return ('','ok','call to get suffix not in course context');
                   7041:         }
                   7042:     }
                   7043: 
                   7044: # construct locking item
                   7045:     my $lockhash = {
                   7046:                       $prefix."\0".'locked_'.$keyid => $who,
                   7047:                    };
                   7048:     my $tries = 0;
                   7049: 
                   7050: # attempt to get lock on nohist_$namespace file
                   7051:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7052:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7053:         $tries ++;
                   7054:         sleep 1;
                   7055:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7056:     }
                   7057: 
                   7058: # attempt to get unique identifier, based on current timestamp
                   7059:     if ($gotlock eq 'ok') {
                   7060:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7061:         my $id = time;
                   7062:         $newid = $id;
1.1172.2.56  raeburn  7063:         if ($idtype eq 'addcode') {
                   7064:             $newid .= &sixnum_code();
                   7065:         }
1.1172.2.13  raeburn  7066:         my $idtries = 0;
                   7067:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7068:             if ($idtype eq 'concat') {
                   7069:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7070:             } elsif ($idtype eq 'addcode') {
                   7071:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7072:             } else {
                   7073:                 $newid ++;
                   7074:             }
                   7075:             $idtries ++;
                   7076:         }
                   7077:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7078:             my %new_item =  (
                   7079:                               $prefix."\0".$newid => $who,
                   7080:                             );
                   7081:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7082:                                                  $cdom,$cnum);
                   7083:             if ($putresult ne 'ok') {
                   7084:                 undef($newid);
                   7085:                 $error = 'error saving new item: '.$putresult;
                   7086:             }
                   7087:         } else {
1.1172.2.56  raeburn  7088:              undef($newid);
1.1172.2.13  raeburn  7089:              $error = ('error: no unique suffix available for the new item ');
                   7090:         }
                   7091: #  remove lock
                   7092:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7093:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7094:     } else {
                   7095:         $error = "error: could not obtain lockfile\n";
                   7096:         $dellock = 'ok';
1.1172.2.58  raeburn  7097:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7098:             $dellock = 'nolock';
                   7099:         }
1.1172.2.13  raeburn  7100:     }
                   7101:     return ($newid,$dellock,$error);
                   7102: }
                   7103: 
1.1172.2.56  raeburn  7104: sub sixnum_code {
                   7105:     my $code;
                   7106:     for (0..6) {
                   7107:         $code .= int( rand(9) );
                   7108:     }
                   7109:     return $code;
                   7110: }
                   7111: 
1.765     albertel 7112: # -------------------------------------------------- portfolio access checking
                   7113: 
                   7114: sub portfolio_access {
1.1172.2.77  raeburn  7115:     my ($requrl,$clientip) = @_;
1.765     albertel 7116:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7117:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7118:     if ($result) {
                   7119:         my %setters;
                   7120:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7121:             my ($startblock,$endblock) =
                   7122:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7123:             if ($startblock && $endblock) {
                   7124:                 return 'B';
                   7125:             }
                   7126:         } else {
                   7127:             my ($startblock,$endblock) =
                   7128:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7129:             if ($startblock && $endblock) {
                   7130:                 return 'B';
                   7131:             }
                   7132:         }
                   7133:     }
1.765     albertel 7134:     if ($result eq 'ok') {
1.766     albertel 7135:        return 'F';
1.765     albertel 7136:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7137:        return 'A';
1.765     albertel 7138:     }
1.766     albertel 7139:     return '';
1.765     albertel 7140: }
                   7141: 
                   7142: sub get_portfolio_access {
1.1172.2.77  raeburn  7143:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7144: 
                   7145:     if (!ref($access_hash)) {
                   7146: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7147: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7148: 						   $file_name);
                   7149: 	$access_hash = $access_controls{$file_name};
                   7150:     }
                   7151: 
1.1172.2.77  raeburn  7152:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7153:     my $now = time;
                   7154:     if (ref($access_hash) eq 'HASH') {
                   7155:         foreach my $key (keys(%{$access_hash})) {
                   7156:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7157:             if ($start > $now) {
                   7158:                 next;
                   7159:             }
                   7160:             if ($end && $end<$now) {
                   7161:                 next;
                   7162:             }
                   7163:             if ($scope eq 'public') {
                   7164:                 $public = $key;
                   7165:                 last;
                   7166:             } elsif ($scope eq 'guest') {
                   7167:                 $guest = $key;
                   7168:             } elsif ($scope eq 'domains') {
                   7169:                 push(@domains,$key);
                   7170:             } elsif ($scope eq 'users') {
                   7171:                 push(@users,$key);
                   7172:             } elsif ($scope eq 'course') {
                   7173:                 push(@courses,$key);
                   7174:             } elsif ($scope eq 'group') {
                   7175:                 push(@groups,$key);
1.1172.2.77  raeburn  7176:             } elsif ($scope eq 'ip') {
                   7177:                 push(@ips,$key);
1.765     albertel 7178:             }
                   7179:         }
                   7180:         if ($public) {
                   7181:             return 'ok';
1.1172.2.77  raeburn  7182:         } elsif (@ips > 0) {
                   7183:             my $allowed;
                   7184:             foreach my $ipkey (@ips) {
                   7185:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7186:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7187:                         $allowed = 1;
                   7188:                         last;
                   7189:                     }
                   7190:                 }
                   7191:             }
                   7192:             if ($allowed) {
                   7193:                 return 'ok';
                   7194:             }
1.765     albertel 7195:         }
                   7196:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7197:             if ($guest) {
                   7198:                 return $guest;
                   7199:             }
                   7200:         } else {
                   7201:             if (@domains > 0) {
                   7202:                 foreach my $domkey (@domains) {
                   7203:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7204:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7205:                             return 'ok';
                   7206:                         }
                   7207:                     }
                   7208:                 }
                   7209:             }
                   7210:             if (@users > 0) {
                   7211:                 foreach my $userkey (@users) {
1.865     raeburn  7212:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7213:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7214:                             if (ref($item) eq 'HASH') {
                   7215:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7216:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7217:                                     return 'ok';
                   7218:                                 }
                   7219:                             }
                   7220:                         }
                   7221:                     } 
1.765     albertel 7222:                 }
                   7223:             }
                   7224:             my %roleshash;
                   7225:             my @courses_and_groups = @courses;
                   7226:             push(@courses_and_groups,@groups); 
                   7227:             if (@courses_and_groups > 0) {
                   7228:                 my (%allgroups,%allroles); 
                   7229:                 my ($start,$end,$role,$sec,$group);
                   7230:                 foreach my $envkey (%env) {
1.1060    raeburn  7231:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7232:                         my $cid = $2.'_'.$3; 
                   7233:                         if ($1 eq 'gr') {
                   7234:                             $group = $4;
                   7235:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7236:                         } else {
                   7237:                             if ($4 eq '') {
                   7238:                                 $sec = 'none';
                   7239:                             } else {
                   7240:                                 $sec = $4;
                   7241:                             }
                   7242:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7243:                         }
1.811     albertel 7244:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7245:                         my $cid = $2.'_'.$3;
                   7246:                         if ($4 eq '') {
                   7247:                             $sec = 'none';
                   7248:                         } else {
                   7249:                             $sec = $4;
                   7250:                         }
                   7251:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7252:                     }
                   7253:                 }
                   7254:                 if (keys(%allroles) == 0) {
                   7255:                     return;
                   7256:                 }
                   7257:                 foreach my $key (@courses_and_groups) {
                   7258:                     my %content = %{$$access_hash{$key}};
                   7259:                     my $cnum = $content{'number'};
                   7260:                     my $cdom = $content{'domain'};
                   7261:                     my $cid = $cdom.'_'.$cnum;
                   7262:                     if (!exists($allroles{$cid})) {
                   7263:                         next;
                   7264:                     }    
                   7265:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7266:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7267:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7268:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7269:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7270:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7271:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7272:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7273:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7274:                                         if (grep/^all$/,@sections) {
                   7275:                                             return 'ok';
                   7276:                                         } else {
                   7277:                                             if (grep/^$sec$/,@sections) {
                   7278:                                                 return 'ok';
                   7279:                                             }
                   7280:                                         }
                   7281:                                     }
                   7282:                                 }
                   7283:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7284:                                     if (grep/^none$/,@groups) {
                   7285:                                         return 'ok';
                   7286:                                     }
                   7287:                                 } else {
                   7288:                                     if (grep/^all$/,@groups) {
                   7289:                                         return 'ok';
                   7290:                                     } 
                   7291:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7292:                                         if (grep/^$group$/,@groups) {
                   7293:                                             return 'ok';
                   7294:                                         }
                   7295:                                     }
                   7296:                                 } 
                   7297:                             }
                   7298:                         }
                   7299:                     }
                   7300:                 }
                   7301:             }
                   7302:             if ($guest) {
                   7303:                 return $guest;
                   7304:             }
                   7305:         }
                   7306:     }
                   7307:     return;
                   7308: }
                   7309: 
                   7310: sub course_group_datechecker {
                   7311:     my ($dates,$now,$status) = @_;
                   7312:     my ($start,$end) = split(/\./,$dates);
                   7313:     if (!$start && !$end) {
                   7314:         return 'ok';
                   7315:     }
                   7316:     if (grep/^active$/,@{$status}) {
                   7317:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7318:             return 'ok';
                   7319:         }
                   7320:     }
                   7321:     if (grep/^previous$/,@{$status}) {
                   7322:         if ($end > $now ) {
                   7323:             return 'ok';
                   7324:         }
                   7325:     }
                   7326:     if (grep/^future$/,@{$status}) {
                   7327:         if ($start > $now) {
                   7328:             return 'ok';
                   7329:         }
                   7330:     }
                   7331:     return; 
                   7332: }
                   7333: 
                   7334: sub parse_portfolio_url {
                   7335:     my ($url) = @_;
                   7336: 
                   7337:     my ($type,$udom,$unum,$group,$file_name);
                   7338:     
1.823     albertel 7339:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7340: 	$type = 1;
                   7341:         $udom = $1;
                   7342:         $unum = $2;
                   7343:         $file_name = $3;
1.823     albertel 7344:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7345: 	$type = 2;
                   7346:         $udom = $1;
                   7347:         $unum = $2;
                   7348:         $group = $3;
                   7349:         $file_name = $3.'/'.$4;
                   7350:     }
                   7351:     if (wantarray) {
                   7352: 	return ($type,$udom,$unum,$file_name,$group);
                   7353:     }
                   7354:     return $type;
                   7355: }
                   7356: 
                   7357: sub is_portfolio_url {
                   7358:     my ($url) = @_;
                   7359:     return scalar(&parse_portfolio_url($url));
                   7360: }
                   7361: 
1.798     raeburn  7362: sub is_portfolio_file {
                   7363:     my ($file) = @_;
1.820     raeburn  7364:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7365:         return 1;
                   7366:     }
                   7367:     return;
                   7368: }
                   7369: 
1.976     raeburn  7370: sub usertools_access {
1.1084    raeburn  7371:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7372:     my ($access,%tools);
                   7373:     if ($context eq '') {
                   7374:         $context = 'tools';
                   7375:     }
                   7376:     if ($context eq 'requestcourses') {
                   7377:         %tools = (
                   7378:                       official   => 1,
                   7379:                       unofficial => 1,
1.1006    raeburn  7380:                       community  => 1,
1.1172.2.37  raeburn  7381:                       textbook   => 1,
1.985     raeburn  7382:                  );
1.1172.2.9  raeburn  7383:     } elsif ($context eq 'requestauthor') {
                   7384:         %tools = (
                   7385:                       requestauthor => 1,
                   7386:                  );
1.985     raeburn  7387:     } else {
                   7388:         %tools = (
                   7389:                       aboutme   => 1,
                   7390:                       blog      => 1,
1.1172.2.6  raeburn  7391:                       webdav    => 1,
1.985     raeburn  7392:                       portfolio => 1,
                   7393:                  );
                   7394:     }
1.976     raeburn  7395:     return if (!defined($tools{$tool}));
                   7396: 
1.1172.2.35  raeburn  7397:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7398:         $udom = $env{'user.domain'};
                   7399:         $uname = $env{'user.name'};
                   7400:     }
                   7401: 
1.978     raeburn  7402:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7403:         if ($action ne 'reload') {
1.985     raeburn  7404:             if ($context eq 'requestcourses') {
                   7405:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7406:             } elsif ($context eq 'requestauthor') {
                   7407:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7408:             } else {
                   7409:                 return $env{'environment.availabletools.'.$tool};
                   7410:             }
                   7411:         }
1.976     raeburn  7412:     }
                   7413: 
1.1172.2.9  raeburn  7414:     my ($toolstatus,$inststatus,$envkey);
                   7415:     if ($context eq 'requestauthor') {
                   7416:         $envkey = $context;
                   7417:     } else {
                   7418:         $envkey = $context.'.'.$tool;
                   7419:     }
1.976     raeburn  7420: 
1.985     raeburn  7421:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7422:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7423:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7424:         $inststatus = $env{'environment.inststatus'};
                   7425:     } else {
1.1084    raeburn  7426:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7427:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7428:             $inststatus = $userenvref->{'inststatus'};
                   7429:         } else {
1.1172.2.9  raeburn  7430:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7431:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7432:             $inststatus = $userenv{'inststatus'};
                   7433:         }
1.976     raeburn  7434:     }
                   7435: 
                   7436:     if ($toolstatus ne '') {
                   7437:         if ($toolstatus) {
                   7438:             $access = 1;
                   7439:         } else {
                   7440:             $access = 0;
                   7441:         }
                   7442:         return $access;
                   7443:     }
                   7444: 
1.1084    raeburn  7445:     my ($is_adv,%domdef);
                   7446:     if (ref($is_advref) eq 'HASH') {
                   7447:         $is_adv = $is_advref->{'is_adv'};
                   7448:     } else {
                   7449:         $is_adv = &is_advanced_user($udom,$uname);
                   7450:     }
                   7451:     if (ref($domdefref) eq 'HASH') {
                   7452:         %domdef = %{$domdefref};
                   7453:     } else {
                   7454:         %domdef = &get_domain_defaults($udom);
                   7455:     }
1.976     raeburn  7456:     if (ref($domdef{$tool}) eq 'HASH') {
                   7457:         if ($is_adv) {
                   7458:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7459:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7460:                     $access = 1;
                   7461:                 } else {
                   7462:                     $access = 0;
                   7463:                 }
                   7464:                 return $access;
                   7465:             }
                   7466:         }
                   7467:         if ($inststatus ne '') {
                   7468:             my ($hasaccess,$hasnoaccess);
                   7469:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7470:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7471:                     if ($domdef{$tool}{$affiliation}) {
                   7472:                         $hasaccess = 1;
                   7473:                     } else {
                   7474:                         $hasnoaccess = 1;
                   7475:                     }
                   7476:                 }
                   7477:             }
                   7478:             if ($hasaccess || $hasnoaccess) {
                   7479:                 if ($hasaccess) {
                   7480:                     $access = 1;
                   7481:                 } elsif ($hasnoaccess) {
                   7482:                     $access = 0; 
                   7483:                 }
                   7484:                 return $access;
                   7485:             }
                   7486:         } else {
                   7487:             if ($domdef{$tool}{'default'} ne '') {
                   7488:                 if ($domdef{$tool}{'default'}) {
                   7489:                     $access = 1;
                   7490:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7491:                     $access = 0;
                   7492:                 }
                   7493:                 return $access;
                   7494:             }
                   7495:         }
                   7496:     } else {
1.1172.2.6  raeburn  7497:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7498:             $access = 1;
                   7499:         } else {
                   7500:             $access = 0;
                   7501:         }
1.976     raeburn  7502:         return $access;
                   7503:     }
                   7504: }
                   7505: 
1.1050    raeburn  7506: sub is_course_owner {
                   7507:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7508:     if (($udom eq '') || ($uname eq '')) {
                   7509:         $udom = $env{'user.domain'};
                   7510:         $uname = $env{'user.name'};
                   7511:     }
                   7512:     unless (($udom eq '') || ($uname eq '')) {
                   7513:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7514:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7515:                 return 1;
                   7516:             } else {
                   7517:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7518:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7519:                     return 1;
                   7520:                 }
                   7521:             }
                   7522:         }
                   7523:     }
                   7524:     return;
                   7525: }
                   7526: 
1.976     raeburn  7527: sub is_advanced_user {
                   7528:     my ($udom,$uname) = @_;
1.1085    raeburn  7529:     if ($udom ne '' && $uname ne '') {
                   7530:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7531:             if (wantarray) {
                   7532:                 return ($env{'user.adv'},$env{'user.author'});
                   7533:             } else {
                   7534:                 return $env{'user.adv'};
                   7535:             }
1.1085    raeburn  7536:         }
                   7537:     }
1.976     raeburn  7538:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7539:     my %allroles;
1.1128    raeburn  7540:     my ($is_adv,$is_author);
1.976     raeburn  7541:     foreach my $role (keys(%roleshash)) {
                   7542:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7543:         my $area = '/'.$tdomain.'/'.$trest;
                   7544:         if ($sec ne '') {
                   7545:             $area .= '/'.$sec;
                   7546:         }
                   7547:         if (($area ne '') && ($trole ne '')) {
                   7548:             my $spec=$trole.'.'.$area;
                   7549:             if ($trole =~ /^cr\//) {
                   7550:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7551:             } elsif ($trole ne 'gr') {
                   7552:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7553:             }
1.1128    raeburn  7554:             if ($trole eq 'au') {
                   7555:                 $is_author = 1;
                   7556:             }
1.976     raeburn  7557:         }
                   7558:     }
                   7559:     foreach my $role (keys(%allroles)) {
                   7560:         last if ($is_adv);
                   7561:         foreach my $item (split(/:/,$allroles{$role})) {
                   7562:             if ($item ne '') {
                   7563:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7564:                 if ($privilege eq 'adv') {
                   7565:                     $is_adv = 1;
                   7566:                     last;
                   7567:                 }
                   7568:             }
                   7569:         }
                   7570:     }
1.1128    raeburn  7571:     if (wantarray) {
                   7572:         return ($is_adv,$is_author);
                   7573:     }
1.976     raeburn  7574:     return $is_adv;
                   7575: }
1.798     raeburn  7576: 
1.1035    raeburn  7577: sub check_can_request {
1.1036    raeburn  7578:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7579:     my $canreq = 0;
                   7580:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7581:     my @options = ('approval','validate','autolimit');
                   7582:     my $optregex = join('|',@options);
                   7583:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7584:         foreach my $type (@{$types}) {
                   7585:             if (&usertools_access($env{'user.name'},
                   7586:                                   $env{'user.domain'},
                   7587:                                   $type,undef,'requestcourses')) {
                   7588:                 $canreq ++;
1.1036    raeburn  7589:                 if (ref($request_domains) eq 'HASH') {
                   7590:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7591:                 }
1.1035    raeburn  7592:                 if ($dom eq $env{'user.domain'}) {
                   7593:                     $can_request->{$type} = 1;
                   7594:                 }
                   7595:             }
                   7596:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7597:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7598:                 if (@curr > 0) {
1.1036    raeburn  7599:                     foreach my $item (@curr) {
                   7600:                         if (ref($request_domains) eq 'HASH') {
                   7601:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7602:                             if ($otherdom ne '') {
                   7603:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7604:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7605:                                         push(@{$request_domains->{$type}},$otherdom);
                   7606:                                     }
                   7607:                                 } else {
                   7608:                                     push(@{$request_domains->{$type}},$otherdom);
                   7609:                                 }
                   7610:                             }
                   7611:                         }
                   7612:                     }
                   7613:                     unless($dom eq $env{'user.domain'}) {
                   7614:                         $canreq ++;
1.1035    raeburn  7615:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7616:                             $can_request->{$type} = 1;
                   7617:                         }
                   7618:                     }
                   7619:                 }
                   7620:             }
                   7621:         }
                   7622:     }
                   7623:     return $canreq;
                   7624: }
                   7625: 
1.341     www      7626: # ---------------------------------------------- Custom access rule evaluation
                   7627: 
                   7628: sub customaccess {
                   7629:     my ($priv,$uri)=@_;
1.807     albertel 7630:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7631:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7632:     $udom = &LONCAPA::clean_domain($udom);
                   7633:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7634:     my $access=0;
1.800     albertel 7635:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7636: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7637: 	if ($type eq 'user') {
                   7638: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7639: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7640: 		if ($tdom) {
                   7641: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7642: 		}
1.896     albertel 7643: 		if ($tuname) {
                   7644: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7645: 		}
                   7646: 		$access=($effect eq 'allow');
                   7647: 		last;
                   7648: 	    }
                   7649: 	} else {
                   7650: 	    if ($role) {
                   7651: 		if ($role ne $urole) { next; }
                   7652: 	    }
                   7653: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7654: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7655: 		if ($tdom) {
                   7656: 		    if ($tdom ne $udom) { next; }
                   7657: 		}
                   7658: 		if ($tcrs) {
                   7659: 		    if ($tcrs ne $ucrs) { next; }
                   7660: 		}
                   7661: 		if ($tsec) {
                   7662: 		    if ($tsec ne $usec) { next; }
                   7663: 		}
                   7664: 		$access=($effect eq 'allow');
                   7665: 		last;
                   7666: 	    }
                   7667: 	    if ($realm eq '' && $role eq '') {
                   7668: 		$access=($effect eq 'allow');
                   7669: 	    }
1.402     bowersj2 7670: 	}
1.341     www      7671:     }
                   7672:     return $access;
                   7673: }
                   7674: 
1.103     harris41 7675: # ------------------------------------------------- Check for a user privilege
1.12      www      7676: 
                   7677: sub allowed {
1.1172.2.65  raeburn  7678:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7679:     my $ver_orguri=$uri;
1.439     www      7680:     $uri=&deversion($uri);
1.152     www      7681:     my $orguri=$uri;
1.52      www      7682:     $uri=&declutter($uri);
1.809     raeburn  7683: 
1.810     raeburn  7684:     if ($priv eq 'evb') {
                   7685: # Evade communication block restrictions for specified role in a course
                   7686:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7687:             return $1;
                   7688:         } else {
                   7689:             return;
                   7690:         }
                   7691:     }
                   7692: 
1.620     albertel 7693:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7694: # Free bre access to adm and meta resources
1.775     albertel 7695:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7696: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7697: 	&& ($priv eq 'bre')) {
1.14      www      7698: 	return 'F';
1.159     www      7699:     }
                   7700: 
1.545     banghart 7701: # Free bre access to user's own portfolio contents
1.714     raeburn  7702:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7703:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7704: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7705:         my %setters;
                   7706:         my ($startblock,$endblock) = 
                   7707:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7708:         if ($startblock && $endblock) {
                   7709:             return 'B';
                   7710:         } else {
                   7711:             return 'F';
                   7712:         }
1.545     banghart 7713:     }
                   7714: 
1.762     raeburn  7715: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7716:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7717:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7718:         if (exists($env{'request.course.id'})) {
                   7719:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7720:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7721:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7722:                 my $courseprivid=$env{'request.course.id'};
                   7723:                 $courseprivid=~s/\_/\//;
                   7724:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7725:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7726:                     return $1; 
1.762     raeburn  7727:                 } else {
                   7728:                     if ($env{'request.course.sec'}) {
                   7729:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7730:                     }
                   7731:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7732:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7733:                         return $2;
                   7734:                     }
1.714     raeburn  7735:                 }
                   7736:             }
                   7737:         }
                   7738:     }
                   7739: 
1.159     www      7740: # Free bre to public access
                   7741: 
                   7742:     if ($priv eq 'bre') {
1.238     www      7743:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7744: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7745:            return 'F'; 
                   7746:         }
1.238     www      7747:         if ($copyright eq 'priv') {
                   7748:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7749: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7750: 		return '';
                   7751:             }
                   7752:         }
                   7753:         if ($copyright eq 'domain') {
                   7754:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7755: 	    unless (($env{'user.domain'} eq $1) ||
                   7756:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7757: 		return '';
                   7758:             }
1.262     matthew  7759:         }
1.620     albertel 7760:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7761:             # Library role, so allow browsing of resources in this domain.
                   7762:             return 'F';
1.238     www      7763:         }
1.341     www      7764:         if ($copyright eq 'custom') {
                   7765: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7766:         }
1.14      www      7767:     }
1.264     matthew  7768:     # Domain coordinator is trying to create a course
1.620     albertel 7769:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7770:         # uri is the requested domain in this case.
                   7771:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7772:         # a role of dc for the domain in question.
1.620     albertel 7773:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7774:     }
1.29      www      7775: 
1.52      www      7776:     my $thisallowed='';
                   7777:     my $statecond=0;
                   7778:     my $courseprivid='';
                   7779: 
1.1039    raeburn  7780:     my $ownaccess;
1.1043    raeburn  7781:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7782:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7783:         if ($uri eq '') {
                   7784:             $ownaccess = 1;
                   7785:         } else {
                   7786:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7787:                 my $udom = $env{'user.domain'};
                   7788:                 my $uname = $env{'user.name'};
                   7789:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7790:                     $ownaccess = 1;
1.1040    raeburn  7791:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7792:                     unless ($uri =~ m{\.\./}) {
                   7793:                         $ownaccess = 1;
                   7794:                     }
                   7795:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7796:                     my $now = time;
                   7797:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7798:                         my $adom = $1;
                   7799:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7800:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7801:                                 my ($start,$end) = split('.',$env{$key});
                   7802:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7803:                                     $ownaccess = 1;
                   7804:                                     last;
                   7805:                                 }
                   7806:                             }
                   7807:                         }
                   7808:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7809:                         my $adom = $1;
                   7810:                         my $aname = $2;
1.1042    raeburn  7811:                         foreach my $role ('ca','aa') { 
                   7812:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7813:                                 my ($start,$end) =
                   7814:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7815:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7816:                                     $ownaccess = 1;
                   7817:                                     last;
                   7818:                                 }
1.1039    raeburn  7819:                             }
                   7820:                         }
                   7821:                     }
                   7822:                 }
                   7823:             }
                   7824:         }
                   7825:     }
                   7826: 
1.52      www      7827: # Course
                   7828: 
1.620     albertel 7829:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7830:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7831:             $thisallowed.=$1;
                   7832:         }
1.52      www      7833:     }
1.29      www      7834: 
1.52      www      7835: # Domain
                   7836: 
1.620     albertel 7837:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7838:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7839:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7840:             $thisallowed.=$1;
                   7841:         }
1.12      www      7842:     }
1.52      www      7843: 
1.1141    raeburn  7844: # User who is not author or co-author might still be able to edit
                   7845: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7846:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7847:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7848:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7849:             $thisallowed.=$1;
                   7850:         }
                   7851:     }
                   7852: 
1.52      www      7853: # Course: uri itself is a course
1.66      www      7854:     my $courseuri=$uri;
                   7855:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7856:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7857: 
1.620     albertel 7858:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7859:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7860:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7861:             $thisallowed.=$1;
                   7862:         }
1.12      www      7863:     }
1.29      www      7864: 
1.665     albertel 7865: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7866: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7867:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7868: 	$thisallowed='';
1.671     raeburn  7869:         my ($match)=&is_on_map($uri);
                   7870:         if ($match) {
                   7871:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7872:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  7873:                 my $value = $1;
                   7874:                 if ($noblockcheck) {
                   7875:                     $thisallowed.=$value;
1.1162    raeburn  7876:                 } else {
1.1172.2.65  raeburn  7877:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7878:                     if (@blockers > 0) {
                   7879:                         $thisallowed = 'B';
                   7880:                     } else {
                   7881:                         $thisallowed.=$value;
                   7882:                     }
1.1162    raeburn  7883:                 }
1.671     raeburn  7884:             }
                   7885:         } else {
1.705     albertel 7886:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7887:             if ($refuri) {
                   7888:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7889:                     $thisallowed='F';
1.671     raeburn  7890:                 } else {
                   7891:                     $refuri=&declutter($refuri);
                   7892:                     my ($match) = &is_on_map($refuri);
                   7893:                     if ($match) {
1.1172.2.65  raeburn  7894:                         if ($noblockcheck) {
1.1162    raeburn  7895:                             $thisallowed='F';
1.1172.2.65  raeburn  7896:                         } else {
                   7897:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7898:                             if (@blockers > 0) {
                   7899:                                 $thisallowed = 'B';
                   7900:                             } else {
                   7901:                                 $thisallowed='F';
                   7902:                             }
1.1162    raeburn  7903:                         }
1.671     raeburn  7904:                     }
1.669     raeburn  7905:                 }
1.671     raeburn  7906:             }
                   7907:         }
1.314     www      7908:     }
1.492     albertel 7909: 
1.766     albertel 7910:     if ($priv eq 'bre'
                   7911: 	&& $thisallowed ne 'F' 
                   7912: 	&& $thisallowed ne '2'
                   7913: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  7914: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7915:     }
                   7916:     
1.52      www      7917: # Full access at system, domain or course-wide level? Exit.
1.29      www      7918:     if ($thisallowed=~/F/) {
                   7919: 	return 'F';
                   7920:     }
                   7921: 
1.52      www      7922: # If this is generating or modifying users, exit with special codes
1.29      www      7923: 
1.643     www      7924:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7925: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7926: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7927: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7928: 	    unless ($auname) { return $thisallowed; }
                   7929: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7930: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7931: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7932: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7933: 	}
1.52      www      7934: 	return $thisallowed;
                   7935:     }
                   7936: #
1.103     harris41 7937: # Gathered so far: system, domain and course wide privileges
1.52      www      7938: #
                   7939: # Course: See if uri or referer is an individual resource that is part of 
                   7940: # the course
                   7941: 
1.620     albertel 7942:     if ($env{'request.course.id'}) {
1.232     www      7943: 
1.620     albertel 7944:        $courseprivid=$env{'request.course.id'};
                   7945:        if ($env{'request.course.sec'}) {
                   7946:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7947:        }
                   7948:        $courseprivid=~s/\_/\//;
                   7949:        my $checkreferer=1;
1.232     www      7950:        my ($match,$cond)=&is_on_map($uri);
                   7951:        if ($match) {
                   7952:            $statecond=$cond;
1.620     albertel 7953:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7954:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7955:                my $value = $1;
                   7956:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  7957:                    if ($noblockcheck) {
1.1162    raeburn  7958:                        $thisallowed.=$value;
1.1172.2.65  raeburn  7959:                    } else {
                   7960:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7961:                        if (@blockers > 0) {
                   7962:                            $thisallowed = 'B';
                   7963:                        } else {
                   7964:                            $thisallowed.=$value;
                   7965:                        }
1.1162    raeburn  7966:                    }
                   7967:                } else {
                   7968:                    $thisallowed.=$value;
                   7969:                }
1.52      www      7970:                $checkreferer=0;
                   7971:            }
1.29      www      7972:        }
1.83      www      7973:        
1.148     www      7974:        if ($checkreferer) {
1.620     albertel 7975: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7976:             unless ($refuri) {
1.800     albertel 7977:                 foreach my $key (keys(%env)) {
                   7978: 		    if ($key=~/^httpref\..*\*/) {
                   7979: 			my $pattern=$key;
1.156     www      7980:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7981:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7982:                         $pattern=~s/\//\\\//g;
1.152     www      7983:                         if ($orguri=~/$pattern/) {
1.800     albertel 7984: 			    $refuri=$env{$key};
1.148     www      7985:                         }
                   7986:                     }
1.191     harris41 7987:                 }
1.148     www      7988:             }
1.232     www      7989: 
1.148     www      7990:          if ($refuri) { 
1.152     www      7991: 	  $refuri=&declutter($refuri);
1.232     www      7992:           my ($match,$cond)=&is_on_map($refuri);
                   7993:             if ($match) {
                   7994:               my $refstatecond=$cond;
1.620     albertel 7995:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7996:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7997:                   my $value = $1;
                   7998:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  7999:                       if ($noblockcheck) {
1.1162    raeburn  8000:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8001:                       } else {
                   8002:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8003:                           if (@blockers > 0) {
                   8004:                               $thisallowed = 'B';
                   8005:                           } else {
                   8006:                               $thisallowed.=$value;
                   8007:                           }
1.1162    raeburn  8008:                       }
                   8009:                   } else {
                   8010:                       $thisallowed.=$value;
                   8011:                   }
1.53      www      8012:                   $uri=$refuri;
                   8013:                   $statecond=$refstatecond;
1.52      www      8014:               }
                   8015:           }
1.148     www      8016:         }
1.29      www      8017:        }
1.52      www      8018:    }
1.29      www      8019: 
1.52      www      8020: #
1.103     harris41 8021: # Gathered now: all privileges that could apply, and condition number
1.52      www      8022: # 
                   8023: #
                   8024: # Full or no access?
                   8025: #
1.29      www      8026: 
1.52      www      8027:     if ($thisallowed=~/F/) {
                   8028: 	return 'F';
                   8029:     }
1.29      www      8030: 
1.52      www      8031:     unless ($thisallowed) {
                   8032:         return '';
                   8033:     }
1.29      www      8034: 
1.52      www      8035: # Restrictions exist, deal with them
                   8036: #
                   8037: #   C:according to course preferences
                   8038: #   R:according to resource settings
                   8039: #   L:unless locked
                   8040: #   X:according to user session state
                   8041: #
                   8042: 
                   8043: # Possibly locked functionality, check all courses
1.54      www      8044: # Locks might take effect only after 10 minutes cache expiration for other
                   8045: # courses, and 2 minutes for current course
1.52      www      8046: 
                   8047:     my $envkey;
                   8048:     if ($thisallowed=~/L/) {
1.1000    raeburn  8049:         foreach $envkey (keys(%env)) {
1.54      www      8050:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8051:                my $courseid=$2;
                   8052:                my $roleid=$1.'.'.$2;
1.92      www      8053:                $courseid=~s/^\///;
1.54      www      8054:                my $expiretime=600;
1.620     albertel 8055:                if ($env{'request.role'} eq $roleid) {
1.54      www      8056: 		  $expiretime=120;
                   8057:                }
                   8058: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8059:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8060:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8061: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8062:                }
1.620     albertel 8063:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8064:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8065: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8066:                        &log($env{'user.domain'},$env{'user.name'},
                   8067:                             $env{'user.home'},
1.57      www      8068:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8069:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8070:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8071: 		       return '';
                   8072:                    }
                   8073:                }
1.620     albertel 8074:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8075:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8076: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8077:                        &log($env{'user.domain'},$env{'user.name'},
                   8078:                             $env{'user.home'},
1.57      www      8079:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8080:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8081:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8082: 		       return '';
                   8083:                    }
                   8084:                }
                   8085: 	   }
1.29      www      8086:        }
1.52      www      8087:     }
                   8088:    
                   8089: #
                   8090: # Rest of the restrictions depend on selected course
                   8091: #
                   8092: 
1.620     albertel 8093:     unless ($env{'request.course.id'}) {
1.766     albertel 8094: 	if ($thisallowed eq 'A') {
                   8095: 	    return 'A';
1.814     raeburn  8096:         } elsif ($thisallowed eq 'B') {
                   8097:             return 'B';
1.766     albertel 8098: 	} else {
                   8099: 	    return '1';
                   8100: 	}
1.52      www      8101:     }
1.29      www      8102: 
1.52      www      8103: #
                   8104: # Now user is definitely in a course
                   8105: #
1.53      www      8106: 
                   8107: 
                   8108: # Course preferences
                   8109: 
                   8110:    if ($thisallowed=~/C/) {
1.620     albertel 8111:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8112:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8113:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8114: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8115: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8116: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8117: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8118: 			$env{'request.course.id'});
                   8119: 	   }
1.237     www      8120:            return '';
                   8121:        }
                   8122: 
1.620     albertel 8123:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8124: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8125: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8126: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8127: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8128: 			$env{'request.course.id'});
                   8129: 	   }
1.54      www      8130:            return '';
                   8131:        }
1.53      www      8132:    }
                   8133: 
                   8134: # Resource preferences
                   8135: 
                   8136:    if ($thisallowed=~/R/) {
1.620     albertel 8137:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8138:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8139: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8140: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8141: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8142: 	   }
                   8143: 	   return '';
1.54      www      8144:        }
1.53      www      8145:    }
1.30      www      8146: 
1.246     www      8147: # Restricted by state or randomout?
1.30      www      8148: 
1.52      www      8149:    if ($thisallowed=~/X/) {
1.620     albertel 8150:       if ($env{'acc.randomout'}) {
1.579     albertel 8151: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8152:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8153:             return ''; 
                   8154:          }
1.247     www      8155:       }
                   8156:       if (&condval($statecond)) {
1.52      www      8157: 	 return '2';
                   8158:       } else {
                   8159:          return '';
                   8160:       }
                   8161:    }
1.30      www      8162: 
1.766     albertel 8163:     if ($thisallowed eq 'A') {
                   8164: 	return 'A';
1.814     raeburn  8165:     } elsif ($thisallowed eq 'B') {
                   8166:         return 'B';
1.766     albertel 8167:     }
1.52      www      8168:    return 'F';
1.232     www      8169: }
1.1162    raeburn  8170: 
1.1172.2.13  raeburn  8171: # ------------------------------------------- Check construction space access
                   8172: 
                   8173: sub constructaccess {
                   8174:     my ($url,$setpriv)=@_;
                   8175: 
                   8176: # We do not allow editing of previous versions of files
                   8177:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8178: 
                   8179: # Get username and domain from URL
                   8180:     my ($ownername,$ownerdomain,$ownerhome);
                   8181: 
                   8182:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8183:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8184: 
                   8185: # The URL does not really point to any authorspace, forget it
                   8186:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8187: 
                   8188: # Now we need to see if the user has access to the authorspace of
                   8189: # $ownername at $ownerdomain
                   8190: 
                   8191:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8192: # Real author for this?
                   8193:        $ownerhome = $env{'user.home'};
                   8194:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8195:           return ($ownername,$ownerdomain,$ownerhome);
                   8196:        }
                   8197:     } else {
                   8198: # Co-author for this?
                   8199:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8200:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8201:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8202:             return ($ownername,$ownerdomain,$ownerhome);
                   8203:         }
                   8204:     }
                   8205: 
                   8206: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8207: # we might as well leave
                   8208:    unless ($setpriv) { return ''; }
                   8209: 
                   8210: # Backdoor access?
                   8211:     my $allowed=&allowed('eco',$ownerdomain);
                   8212: # Nope
                   8213:     unless ($allowed) { return ''; }
                   8214: # Looks like we may have access, but could be locked by the owner of the construction space
                   8215:     if ($allowed eq 'U') {
                   8216:         my %blocked=&get('environment',['domcoord.author'],
                   8217:                          $ownerdomain,$ownername);
                   8218: # Is blocked by owner
                   8219:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8220:     }
                   8221:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8222: # Grant temporary access
                   8223:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8224:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8225:         if (!$update) { $update = $then; }
                   8226:         my $refresh=$env{'user.refresh.time'};
                   8227:         if (!$refresh) { $refresh = $update; }
                   8228:         my $now = time;
                   8229:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8230:                            $now,'ca','constructaccess');
                   8231:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8232:         return($ownername,$ownerdomain,$ownerhome);
                   8233:     }
                   8234: # No business here
                   8235:     return '';
                   8236: }
                   8237: 
1.1172.2.66  raeburn  8238: # ----------------------------------------------------------- Content Blocking
                   8239: 
                   8240: {
                   8241: # Caches for faster Course Contents display where content blocking
                   8242: # is in operation (i.e., interval param set) for timed quiz.
                   8243: #
                   8244: # User for whom data are being temporarily cached.
                   8245: my $cacheduser='';
                   8246: # Cached blockers for this user (a hash of blocking items).
                   8247: my %cachedblockers=();
                   8248: # When the data were last cached.
                   8249: my $cachedlast='';
                   8250: 
                   8251: sub load_all_blockers {
                   8252:     my ($uname,$udom,$blocks)=@_;
                   8253:     if (($uname ne '') && ($udom ne '')) {
                   8254:         if (($cacheduser eq $uname.':'.$udom) &&
                   8255:             (abs($cachedlast-time)<5)) {
                   8256:             return;
                   8257:         }
                   8258:     }
                   8259:     $cachedlast=time;
                   8260:     $cacheduser=$uname.':'.$udom;
                   8261:     %cachedblockers = &get_commblock_resources($blocks);
                   8262: }
                   8263: 
1.1162    raeburn  8264: sub get_comm_blocks {
                   8265:     my ($cdom,$cnum) = @_;
                   8266:     if ($cdom eq '' || $cnum eq '') {
                   8267:         return unless ($env{'request.course.id'});
                   8268:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8269:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8270:     }
                   8271:     my %commblocks;
                   8272:     my $hashid=$cdom.'_'.$cnum;
                   8273:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8274:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8275:         %commblocks = %{$blocksref};
                   8276:     } else {
                   8277:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8278:         my $cachetime = 600;
                   8279:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8280:     }
                   8281:     return %commblocks;
                   8282: }
                   8283: 
1.1172.2.66  raeburn  8284: sub get_commblock_resources {
                   8285:     my ($blocks) = @_;
                   8286:     my %blockers = ();
                   8287:     return %blockers unless ($env{'request.course.id'});
                   8288:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8289:     my %commblocks;
                   8290:     if (ref($blocks) eq 'HASH') {
                   8291:         %commblocks = %{$blocks};
                   8292:     } else {
                   8293:         %commblocks = &get_comm_blocks();
                   8294:     }
1.1172.2.66  raeburn  8295:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8296:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8297:     return %blockers unless (ref($navmap));
                   8298:     my $now = time;
1.1162    raeburn  8299:     foreach my $block (keys(%commblocks)) {
                   8300:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8301:             my ($start,$end) = ($1,$2);
                   8302:             if ($start <= $now && $end >= $now) {
                   8303:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8304:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8305:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8306:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8307:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8308:                             }
                   8309:                         }
                   8310:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8311:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8312:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8313:                             }
                   8314:                         }
                   8315:                     }
                   8316:                 }
                   8317:             }
                   8318:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8319:             my $item = $1;
1.1163    raeburn  8320:             my @to_test;
1.1162    raeburn  8321:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8322:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8323:                     my @interval;
                   8324:                     my $type = 'map';
                   8325:                     if ($item eq 'course') {
                   8326:                         $type = 'course';
                   8327:                         @interval=&EXT("resource.0.interval");
                   8328:                     } else {
                   8329:                         if ($item =~ /___\d+___/) {
                   8330:                             $type = 'resource';
                   8331:                             @interval=&EXT("resource.0.interval",$item);
                   8332:                             if (ref($navmap)) {
                   8333:                                 my $res = $navmap->getBySymb($item);
                   8334:                                 push(@to_test,$res);
                   8335:                             }
1.1162    raeburn  8336:                         } else {
1.1172.2.66  raeburn  8337:                             my $mapsymb = &symbread($item,1);
                   8338:                             if ($mapsymb) {
                   8339:                                 if (ref($navmap)) {
                   8340:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8341:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8342:                                     foreach my $res (@to_test) {
                   8343:                                         my $symb = $res->symb();
                   8344:                                         next if ($symb eq $mapsymb);
                   8345:                                         if ($symb ne '') {
                   8346:                                             @interval=&EXT("resource.0.interval",$symb);
                   8347:                                             if ($interval[1] eq 'map') {
                   8348:                                                 last;
1.1162    raeburn  8349:                                             }
                   8350:                                         }
                   8351:                                     }
                   8352:                                 }
                   8353:                             }
                   8354:                         }
1.1172.2.66  raeburn  8355:                     }
                   8356:                     if ($interval[0] =~ /^\d+$/) {
                   8357:                         my $first_access;
                   8358:                         if ($type eq 'resource') {
                   8359:                             $first_access=&get_first_access($interval[1],$item);
                   8360:                         } elsif ($type eq 'map') {
                   8361:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8362:                         } else {
                   8363:                             $first_access=&get_first_access($interval[1]);
                   8364:                         }
                   8365:                         if ($first_access) {
                   8366:                             my $timesup = $first_access+$interval[0];
                   8367:                             if ($timesup > $now) {
                   8368:                                 my $activeblock;
                   8369:                                 foreach my $res (@to_test) {
                   8370:                                     if ($res->answerable()) {
                   8371:                                         $activeblock = 1;
                   8372:                                         last;
                   8373:                                     }
                   8374:                                 }
                   8375:                                 if ($activeblock) {
                   8376:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8377:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8378:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8379:                                          }
                   8380:                                     }
                   8381:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8382:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8383:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8384:                                         }
1.1162    raeburn  8385:                                     }
                   8386:                                 }
                   8387:                             }
                   8388:                         }
                   8389:                     }
                   8390:                 }
                   8391:             }
                   8392:         }
                   8393:     }
1.1172.2.66  raeburn  8394:     return %blockers;
1.1162    raeburn  8395: }
                   8396: 
1.1172.2.66  raeburn  8397: sub has_comm_blocking {
                   8398:     my ($priv,$symb,$uri,$blocks) = @_;
                   8399:     my @blockers;
                   8400:     return unless ($env{'request.course.id'});
                   8401:     return unless ($priv eq 'bre');
                   8402:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8403:     return if ($env{'request.state'} eq 'construct');
                   8404:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8405:     return unless (keys(%cachedblockers) > 0);
                   8406:     my (%possibles,@symbs);
                   8407:     if (!$symb) {
                   8408:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8409:     }
1.1172.2.66  raeburn  8410:     if ($symb) {
                   8411:         @symbs = ($symb);
                   8412:     } elsif (keys(%possibles)) {
                   8413:         @symbs = keys(%possibles);
                   8414:     }
                   8415:     my $noblock;
                   8416:     foreach my $symb (@symbs) {
                   8417:         last if ($noblock);
                   8418:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8419:         foreach my $block (keys(%cachedblockers)) {
                   8420:             if ($block =~ /^firstaccess____(.+)$/) {
                   8421:                 my $item = $1;
                   8422:                 if (($item eq $map) || ($item eq $symb)) {
                   8423:                     $noblock = 1;
                   8424:                     last;
                   8425:                 }
1.1162    raeburn  8426:             }
1.1172.2.66  raeburn  8427:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8428:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8429:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8430:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8431:                             push(@blockers,$block);
                   8432:                         }
                   8433:                     }
                   8434:                 }
                   8435:             }
                   8436:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8437:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8438:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8439:                         push(@blockers,$block);
                   8440:                     }
                   8441:                 }
1.1162    raeburn  8442:             }
                   8443:         }
                   8444:     }
1.1172.2.66  raeburn  8445:     return if ($noblock);
                   8446:     return @blockers;
                   8447: }
1.1162    raeburn  8448: }
                   8449: 
1.1172.2.66  raeburn  8450: # -------------------------------- Deversion and split uri into path an filename
                   8451: 
1.1133    foxr     8452: #
1.1172.2.66  raeburn  8453: #   Removes the version from a URI and
1.1133    foxr     8454: #   splits it in to its filename and path to the filename.
                   8455: #   Seems like File::Basename could have done this more clearly.
                   8456: #   Parameters:
                   8457: #      $uri   - input URI
                   8458: #   Returns:
                   8459: #     Two element list consisting of 
                   8460: #     $pathname  - the URI up to and excluding the trailing /
                   8461: #     $filename  - The part of the URI following the last /
                   8462: #  NOTE:
                   8463: #    Another realization of this is simply:
                   8464: #    use File::Basename;
                   8465: #    ...
                   8466: #    $uri = shift;
                   8467: #    $filename = basename($uri);
                   8468: #    $path     = dirname($uri);
                   8469: #    return ($filename, $path);
                   8470: #
                   8471: #     The implementation below is probably faster however.
                   8472: #
1.710     albertel 8473: sub split_uri_for_cond {
                   8474:     my $uri=&deversion(&declutter(shift));
                   8475:     my @uriparts=split(/\//,$uri);
                   8476:     my $filename=pop(@uriparts);
                   8477:     my $pathname=join('/',@uriparts);
                   8478:     return ($pathname,$filename);
                   8479: }
1.232     www      8480: # --------------------------------------------------- Is a resource on the map?
                   8481: 
                   8482: sub is_on_map {
1.710     albertel 8483:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8484:     #Trying to find the conditional for the file
1.620     albertel 8485:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8486: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8487:     if ($match) {
1.289     bowersj2 8488: 	return (1,$1);
                   8489:     } else {
1.434     www      8490: 	return (0,0);
1.289     bowersj2 8491:     }
1.12      www      8492: }
                   8493: 
1.427     www      8494: # --------------------------------------------------------- Get symb from alias
                   8495: 
                   8496: sub get_symb_from_alias {
                   8497:     my $symb=shift;
                   8498:     my ($map,$resid,$url)=&decode_symb($symb);
                   8499: # Already is a symb
                   8500:     if ($url) { return $symb; }
                   8501: # Must be an alias
                   8502:     my $aliassymb='';
                   8503:     my %bighash;
1.620     albertel 8504:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8505:                             &GDBM_READER(),0640)) {
                   8506:         my $rid=$bighash{'mapalias_'.$symb};
                   8507: 	if ($rid) {
                   8508: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8509: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8510: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8511: 	}
                   8512:         untie %bighash;
                   8513:     }
                   8514:     return $aliassymb;
                   8515: }
                   8516: 
1.12      www      8517: # ----------------------------------------------------------------- Define Role
                   8518: 
                   8519: sub definerole {
                   8520:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8521:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8522:     foreach my $role (split(':',$sysrole)) {
                   8523: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8524:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8525:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8526: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8527:                return "refused:s:$crole&$cqual"; 
                   8528:             }
                   8529:         }
1.191     harris41 8530:     }
1.800     albertel 8531:     foreach my $role (split(':',$domrole)) {
                   8532: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8533:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8534:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8535: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8536:                return "refused:d:$crole&$cqual"; 
                   8537:             }
                   8538:         }
1.191     harris41 8539:     }
1.800     albertel 8540:     foreach my $role (split(':',$courole)) {
                   8541: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8542:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8543:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8544: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8545:                return "refused:c:$crole&$cqual"; 
                   8546:             }
                   8547:         }
1.191     harris41 8548:     }
1.1172.2.84  raeburn  8549:     my $uhome;
                   8550:     if (($uname ne '') && ($udom ne '')) {
                   8551:         $uhome = &homeserver($uname,$udom);
                   8552:         return $uhome if ($uhome eq 'no_host');
                   8553:     } else {
                   8554:         $uname = $env{'user.name'};
                   8555:         $udom = $env{'user.domain'};
                   8556:         $uhome = $env{'user.home'};
                   8557:     }
1.620     albertel 8558:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8559:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8560:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8561:     return reply($command,$uhome);
1.12      www      8562:   } else {
                   8563:     return 'refused';
                   8564:   }
1.105     harris41 8565: }
                   8566: 
                   8567: # ---------------- Make a metadata query against the network of library servers
                   8568: 
                   8569: sub metadata_query {
1.1172.2.33  raeburn  8570:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8571:     my %rhash;
1.845     albertel 8572:     my %libserv = &all_library();
1.244     matthew  8573:     my @server_list = (defined($server_array) ? @$server_array
                   8574:                                               : keys(%libserv) );
                   8575:     for my $server (@server_list) {
1.1172.2.33  raeburn  8576:         my $domains = '';
                   8577:         if (ref($domains_hash) eq 'HASH') {
                   8578:             $domains = $domains_hash->{$server};    
                   8579:         }
1.118     harris41 8580: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8581: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8582: 	    $rhash{$server}=$reply;
                   8583: 	}
                   8584: 	else {
                   8585: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8586: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8587: 			     $server);
                   8588: 	    $rhash{$server}=$reply;
                   8589: 	}
1.112     harris41 8590:     }
1.118     harris41 8591:     return \%rhash;
1.240     www      8592: }
                   8593: 
                   8594: # ----------------------------------------- Send log queries and wait for reply
                   8595: 
                   8596: sub log_query {
                   8597:     my ($uname,$udom,$query,%filters)=@_;
                   8598:     my $uhome=&homeserver($uname,$udom);
                   8599:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8600:     my $uhost=&hostname($uhome);
1.800     albertel 8601:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8602:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8603:                        $uhome);
1.479     albertel 8604:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8605:     return get_query_reply($queryid);
                   8606: }
                   8607: 
1.818     raeburn  8608: # -------------------------- Update MySQL table for portfolio file
                   8609: 
                   8610: sub update_portfolio_table {
1.821     raeburn  8611:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8612:     if ($group ne '') {
                   8613:         $file_name =~s /^\Q$group\E//;
                   8614:     }
1.818     raeburn  8615:     my $homeserver = &homeserver($uname,$udom);
                   8616:     my $queryid=
1.821     raeburn  8617:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8618:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8619:     my $reply = &get_query_reply($queryid);
                   8620:     return $reply;
                   8621: }
                   8622: 
1.899     raeburn  8623: # -------------------------- Update MySQL allusers table
                   8624: 
                   8625: sub update_allusers_table {
                   8626:     my ($uname,$udom,$names) = @_;
                   8627:     my $homeserver = &homeserver($uname,$udom);
                   8628:     my $queryid=
                   8629:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8630:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8631:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8632:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8633:                'generation='.&escape($names->{'generation'}).'%%'.
                   8634:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8635:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8636:     return;
1.899     raeburn  8637: }
                   8638: 
1.508     raeburn  8639: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8640: 
                   8641: sub fetch_enrollment_query {
1.511     raeburn  8642:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8643:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8644:     my $maxtries = 1;
1.508     raeburn  8645:     if ($context eq 'automated') {
                   8646:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8647:         $sleep = 2;
                   8648:         $loopmax = 100;
1.547     raeburn  8649:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8650:     } else {
                   8651:         $homeserver = &homeserver($cnum,$dom);
                   8652:     }
1.838     albertel 8653:     my $host=&hostname($homeserver);
1.506     raeburn  8654:     my $cmd = '';
1.1000    raeburn  8655:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8656:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8657:     }
                   8658:     $cmd =~ s/%%$//;
                   8659:     $cmd = &escape($cmd);
                   8660:     my $query = 'fetchenrollment';
1.620     albertel 8661:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8662:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8663:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8664:         return 'error: '.$queryid;
                   8665:     }
1.1172.2.93  raeburn  8666:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8667:     my $tries = 1;
                   8668:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8669:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8670:         $tries ++;
                   8671:     }
1.526     raeburn  8672:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8673:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8674:     } else {
1.901     albertel 8675:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8676:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8677:             foreach my $line (@responses) {
                   8678:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8679:                 $$replyref{$key} = $value;
                   8680:             }
                   8681:         } else {
1.1117    foxr     8682:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8683:             foreach my $line (@responses) {
                   8684:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8685:                 $$replyref{$key} = $value;
                   8686:                 if ($value > 0) {
1.800     albertel 8687:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8688:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8689:                         my $destname = $pathname.'/'.$filename;
                   8690:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8691:                         if ($xml_classlist =~ /^error/) {
                   8692:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8693:                         } else {
1.1172.2.96  raeburn  8694:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8695:                                 print FILE &unescape($xml_classlist);
                   8696:                                 close(FILE);
1.526     raeburn  8697:                             } else {
                   8698:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8699:                             }
                   8700:                         }
                   8701:                     }
                   8702:                 }
                   8703:             }
                   8704:         }
                   8705:         return 'ok';
                   8706:     }
                   8707:     return 'error';
                   8708: }
                   8709: 
1.242     www      8710: sub get_query_reply {
1.1172.2.79  raeburn  8711:     my ($queryid,$sleep,$loopmax) = @_;
                   8712:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8713:         $sleep = 0.2;
                   8714:     }
                   8715:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8716:         $loopmax = 100;
                   8717:     }
1.1117    foxr     8718:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8719:     my $reply='';
1.1172.2.79  raeburn  8720:     for (1..$loopmax) {
                   8721: 	sleep($sleep);
1.240     www      8722:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8723: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8724: 		$reply = join('',<$fh>);
                   8725: 		close($fh);
1.240     www      8726: 	   } else { return 'error: reply_file_error'; }
1.242     www      8727:            return &unescape($reply);
                   8728: 	}
1.240     www      8729:     }
1.242     www      8730:     return 'timeout:'.$queryid;
1.240     www      8731: }
                   8732: 
                   8733: sub courselog_query {
1.241     www      8734: #
                   8735: # possible filters:
                   8736: # url: url or symb
                   8737: # username
                   8738: # domain
                   8739: # action: view, submit, grade
                   8740: # start: timestamp
                   8741: # end: timestamp
                   8742: #
1.240     www      8743:     my (%filters)=@_;
1.620     albertel 8744:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8745:     if ($filters{'url'}) {
                   8746: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8747:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8748:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8749:     }
1.620     albertel 8750:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8751:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8752:     return &log_query($cname,$cdom,'courselog',%filters);
                   8753: }
                   8754: 
                   8755: sub userlog_query {
1.858     raeburn  8756: #
                   8757: # possible filters:
                   8758: # action: log check role
                   8759: # start: timestamp
                   8760: # end: timestamp
                   8761: #
1.240     www      8762:     my ($uname,$udom,%filters)=@_;
                   8763:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8764: }
                   8765: 
1.506     raeburn  8766: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8767: 
                   8768: sub auto_run {
1.508     raeburn  8769:     my ($cnum,$cdom) = @_;
1.876     raeburn  8770:     my $response = 0;
                   8771:     my $settings;
                   8772:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8773:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8774:         $settings = $domconfig{'autoenroll'};
                   8775:         if ($settings->{'run'} eq '1') {
                   8776:             $response = 1;
                   8777:         }
                   8778:     } else {
1.934     raeburn  8779:         my $homeserver;
                   8780:         if (&is_course($cdom,$cnum)) {
                   8781:             $homeserver = &homeserver($cnum,$cdom);
                   8782:         } else {
                   8783:             $homeserver = &domain($cdom,'primary');
                   8784:         }
                   8785:         if ($homeserver ne 'no_host') {
                   8786:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8787:         }
1.876     raeburn  8788:     }
1.506     raeburn  8789:     return $response;
                   8790: }
1.776     albertel 8791: 
1.506     raeburn  8792: sub auto_get_sections {
1.508     raeburn  8793:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8794:     my $homeserver;
                   8795:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8796:         $homeserver = &homeserver($cnum,$cdom);
                   8797:     }
                   8798:     if (!defined($homeserver)) { 
                   8799:         if ($cdom =~ /^$match_domain$/) {
                   8800:             $homeserver = &domain($cdom,'primary');
                   8801:         }
                   8802:     }
                   8803:     my @secs;
                   8804:     if (defined($homeserver)) {
                   8805:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8806:         unless ($response eq 'refused') {
                   8807:             @secs = split(/:/,$response);
                   8808:         }
1.506     raeburn  8809:     }
                   8810:     return @secs;
                   8811: }
1.776     albertel 8812: 
1.506     raeburn  8813: sub auto_new_course {
1.1099    raeburn  8814:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8815:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8816:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8817:     return $response;
                   8818: }
1.776     albertel 8819: 
1.506     raeburn  8820: sub auto_validate_courseID {
1.508     raeburn  8821:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8822:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8823:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8824:     return $response;
                   8825: }
1.776     albertel 8826: 
1.1007    raeburn  8827: sub auto_validate_instcode {
1.1020    raeburn  8828:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8829:     my ($homeserver,$response);
                   8830:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8831:         $homeserver = &homeserver($cnum,$cdom);
                   8832:     }
                   8833:     if (!defined($homeserver)) {
                   8834:         if ($cdom =~ /^$match_domain$/) {
                   8835:             $homeserver = &domain($cdom,'primary');
                   8836:         }
                   8837:     }
1.1065    raeburn  8838:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8839:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  8840:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8841:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8842: }
                   8843: 
1.506     raeburn  8844: sub auto_create_password {
1.873     raeburn  8845:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8846:     my ($homeserver,$response);
1.506     raeburn  8847:     my $create_passwd = 0;
                   8848:     my $authchk = '';
1.873     raeburn  8849:     if ($udom =~ /^$match_domain$/) {
                   8850:         $homeserver = &domain($udom,'primary');
                   8851:     }
                   8852:     if ($homeserver eq '') {
                   8853:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8854:             $homeserver = &homeserver($cnum,$cdom);
                   8855:         }
                   8856:     }
                   8857:     if ($homeserver eq '') {
                   8858:         $authchk = 'nodomain';
1.506     raeburn  8859:     } else {
1.873     raeburn  8860:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8861:         if ($response eq 'refused') {
                   8862:             $authchk = 'refused';
                   8863:         } else {
1.901     albertel 8864:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8865:         }
1.506     raeburn  8866:     }
                   8867:     return ($authparam,$create_passwd,$authchk);
                   8868: }
                   8869: 
1.706     raeburn  8870: sub auto_photo_permission {
                   8871:     my ($cnum,$cdom,$students) = @_;
                   8872:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8873:     my ($outcome,$perm_reqd,$conditions) = 
                   8874: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8875:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8876: 	return (undef,undef);
                   8877:     }
1.706     raeburn  8878:     return ($outcome,$perm_reqd,$conditions);
                   8879: }
                   8880: 
                   8881: sub auto_checkphotos {
                   8882:     my ($uname,$udom,$pid) = @_;
                   8883:     my $homeserver = &homeserver($uname,$udom);
                   8884:     my ($result,$resulttype);
                   8885:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8886: 				   &escape($uname).':'.&escape($pid),
                   8887: 				   $homeserver));
1.709     albertel 8888:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8889: 	return (undef,undef);
                   8890:     }
1.706     raeburn  8891:     if ($outcome) {
                   8892:         ($result,$resulttype) = split(/:/,$outcome);
                   8893:     } 
                   8894:     return ($result,$resulttype);
                   8895: }
                   8896: 
                   8897: sub auto_photochoice {
                   8898:     my ($cnum,$cdom) = @_;
                   8899:     my $homeserver = &homeserver($cnum,$cdom);
                   8900:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8901: 						       &escape($cdom),
                   8902: 						       $homeserver)));
1.709     albertel 8903:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8904: 	return (undef,undef);
                   8905:     }
1.706     raeburn  8906:     return ($update,$comment);
                   8907: }
                   8908: 
                   8909: sub auto_photoupdate {
                   8910:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8911:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8912:     my $host=&hostname($homeserver);
1.706     raeburn  8913:     my $cmd = '';
                   8914:     my $maxtries = 1;
1.800     albertel 8915:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8916:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8917:     }
                   8918:     $cmd =~ s/%%$//;
                   8919:     $cmd = &escape($cmd);
                   8920:     my $query = 'institutionalphotos';
                   8921:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8922:     unless ($queryid=~/^\Q$host\E\_/) {
                   8923:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8924:         return 'error: '.$queryid;
                   8925:     }
                   8926:     my $reply = &get_query_reply($queryid);
                   8927:     my $tries = 1;
                   8928:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8929:         $reply = &get_query_reply($queryid);
                   8930:         $tries ++;
                   8931:     }
                   8932:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8933:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8934:     } else {
                   8935:         my @responses = split(/:/,$reply);
                   8936:         my $outcome = shift(@responses); 
                   8937:         foreach my $item (@responses) {
                   8938:             my ($key,$value) = split(/=/,$item);
                   8939:             $$photo{$key} = $value;
                   8940:         }
                   8941:         return $outcome;
                   8942:     }
                   8943:     return 'error';
                   8944: }
                   8945: 
1.521     raeburn  8946: sub auto_instcode_format {
1.793     albertel 8947:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8948: 	$cat_order) = @_;
1.521     raeburn  8949:     my $courses = '';
1.772     raeburn  8950:     my @homeservers;
1.521     raeburn  8951:     if ($caller eq 'global') {
1.841     albertel 8952: 	my %servers = &get_servers($codedom,'library');
                   8953: 	foreach my $tryserver (keys(%servers)) {
                   8954: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8955: 		push(@homeservers,$tryserver);
                   8956: 	    }
1.584     raeburn  8957:         }
1.1022    raeburn  8958:     } elsif ($caller eq 'requests') {
                   8959:         if ($codedom =~ /^$match_domain$/) {
                   8960:             my $chome = &domain($codedom,'primary');
                   8961:             unless ($chome eq 'no_host') {
                   8962:                 push(@homeservers,$chome);
                   8963:             }
                   8964:         }
1.521     raeburn  8965:     } else {
1.772     raeburn  8966:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8967:     }
1.793     albertel 8968:     foreach my $code (keys(%{$instcodes})) {
                   8969:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8970:     }
                   8971:     chop($courses);
1.772     raeburn  8972:     my $ok_response = 0;
                   8973:     my $response;
                   8974:     while (@homeservers > 0 && $ok_response == 0) {
                   8975:         my $server = shift(@homeservers); 
                   8976:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8977:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8978:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8979: 		split(/:/,$response);
1.772     raeburn  8980:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8981:             push(@{$codetitles},&str2array($codetitles_str));
                   8982:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8983:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8984:             $ok_response = 1;
                   8985:         }
                   8986:     }
                   8987:     if ($ok_response) {
1.521     raeburn  8988:         return 'ok';
1.772     raeburn  8989:     } else {
                   8990:         return $response;
1.521     raeburn  8991:     }
                   8992: }
                   8993: 
1.792     raeburn  8994: sub auto_instcode_defaults {
                   8995:     my ($domain,$returnhash,$code_order) = @_;
                   8996:     my @homeservers;
1.841     albertel 8997: 
                   8998:     my %servers = &get_servers($domain,'library');
                   8999:     foreach my $tryserver (keys(%servers)) {
                   9000: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9001: 	    push(@homeservers,$tryserver);
                   9002: 	}
1.792     raeburn  9003:     }
1.841     albertel 9004: 
1.792     raeburn  9005:     my $response;
1.841     albertel 9006:     foreach my $server (@homeservers) {
1.792     raeburn  9007:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9008:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9009: 	
                   9010: 	foreach my $pair (split(/\&/,$response)) {
                   9011: 	    my ($name,$value)=split(/\=/,$pair);
                   9012: 	    if ($name eq 'code_order') {
                   9013: 		@{$code_order} = split(/\&/,&unescape($value));
                   9014: 	    } else {
                   9015: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9016: 	    }
                   9017: 	}
                   9018: 	return 'ok';
1.792     raeburn  9019:     }
1.841     albertel 9020: 
                   9021:     return $response;
1.1003    raeburn  9022: }
                   9023: 
                   9024: sub auto_possible_instcodes {
1.1007    raeburn  9025:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9026:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9027:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9028:         return;
                   9029:     }
1.1003    raeburn  9030:     my (@homeservers,$uhome);
                   9031:     if (defined(&domain($domain,'primary'))) {
                   9032:         $uhome=&domain($domain,'primary');
                   9033:         push(@homeservers,&domain($domain,'primary'));
                   9034:     } else {
                   9035:         my %servers = &get_servers($domain,'library');
                   9036:         foreach my $tryserver (keys(%servers)) {
                   9037:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9038:                 push(@homeservers,$tryserver);
                   9039:             }
                   9040:         }
                   9041:     }
                   9042:     my $response;
                   9043:     foreach my $server (@homeservers) {
                   9044:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9045:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9046:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9047:             split(':',$response);
                   9048:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9049:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9050:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9051:             my ($name,$value)=split('=',$item);
                   9052:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9053:         }
                   9054:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9055:             my ($name,$value)=split('=',$item);
                   9056:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9057:         }
                   9058:         return 'ok';
                   9059:     }
                   9060:     return $response;
                   9061: }
1.792     raeburn  9062: 
1.1010    raeburn  9063: sub auto_courserequest_checks {
                   9064:     my ($dom) = @_;
1.1020    raeburn  9065:     my ($homeserver,%validations);
                   9066:     if ($dom =~ /^$match_domain$/) {
                   9067:         $homeserver = &domain($dom,'primary');
                   9068:     }
                   9069:     unless ($homeserver eq 'no_host') {
                   9070:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9071:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9072:             my @items = split(/&/,$response);
                   9073:             foreach my $item (@items) {
                   9074:                 my ($key,$value) = split('=',$item);
                   9075:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9076:             }
                   9077:         }
                   9078:     }
1.1010    raeburn  9079:     return %validations; 
                   9080: }
                   9081: 
1.1020    raeburn  9082: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9083:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9084:     my ($homeserver,$response);
                   9085:     if ($dom =~ /^$match_domain$/) {
                   9086:         $homeserver = &domain($dom,'primary');
                   9087:     }
1.1172.2.43  raeburn  9088:     unless ($homeserver eq 'no_host') {
                   9089:         my $customdata;
                   9090:         if (ref($custominfo) eq 'HASH') {
                   9091:             $customdata = &freeze_escape($custominfo);
                   9092:         }
1.1020    raeburn  9093:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9094:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9095:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9096:                                     $customdata,$homeserver));
1.1020    raeburn  9097:     }
                   9098:     return $response;
                   9099: }
                   9100: 
1.777     albertel 9101: sub auto_validate_class_sec {
1.918     raeburn  9102:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9103:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9104:     my $ownerlist;
                   9105:     if (ref($owners) eq 'ARRAY') {
                   9106:         $ownerlist = join(',',@{$owners});
                   9107:     } else {
                   9108:         $ownerlist = $owners;
                   9109:     }
1.773     raeburn  9110:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9111:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9112:     return $response;
                   9113: }
                   9114: 
1.1172.2.94  raeburn  9115: sub auto_validate_instclasses {
                   9116:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9117:     my ($homeserver,%validations);
                   9118:     $homeserver = &homeserver($cnum,$cdom);
                   9119:     unless ($homeserver eq 'no_host') {
                   9120:         my $ownerlist;
                   9121:         if (ref($owners) eq 'ARRAY') {
                   9122:             $ownerlist = join(',',@{$owners});
                   9123:         } else {
                   9124:             $ownerlist = $owners;
                   9125:         }
                   9126:         if (ref($classesref) eq 'HASH') {
                   9127:             my $classes = &freeze_escape($classesref);
                   9128:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9129:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9130:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9131:                 my @items = split(/&/,$response);
                   9132:                 foreach my $item (@items) {
                   9133:                     my ($key,$value) = split('=',$item);
                   9134:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9135:                 }
                   9136:             }
                   9137:         }
                   9138:     }
                   9139:     return %validations;
                   9140: }
                   9141: 
1.1172.2.38  raeburn  9142: sub auto_crsreq_update {
                   9143:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9144:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9145:     my ($homeserver,%crsreqresponse);
                   9146:     if ($cdom =~ /^$match_domain$/) {
                   9147:         $homeserver = &domain($cdom,'primary');
                   9148:     }
                   9149:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9150:         my $info;
                   9151:         if (ref($inbound) eq 'HASH') {
                   9152:             $info = &freeze_escape($inbound);
                   9153:         }
                   9154:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9155:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9156:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9157:                             &escape($title).':'.&escape($code).':'.
                   9158:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9159:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9160:             my @items = split(/&/,$response);
                   9161:             foreach my $item (@items) {
                   9162:                 my ($key,$value) = split('=',$item);
                   9163:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9164:             }
                   9165:         }
                   9166:     }
                   9167:     return \%crsreqresponse;
                   9168: }
                   9169: 
1.1172.2.78  raeburn  9170: sub auto_export_grades {
                   9171:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9172:     my ($homeserver,%exportresponse);
                   9173:     if ($cdom =~ /^$match_domain$/) {
                   9174:         $homeserver = &domain($cdom,'primary');
                   9175:     }
                   9176:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9177:         my $info;
                   9178:         if (ref($inforef) eq 'HASH') {
                   9179:             $info = &freeze_escape($inforef);
                   9180:         }
                   9181:         if (ref($gradesref) eq 'HASH') {
                   9182:             my $grades = &freeze_escape($gradesref);
                   9183:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9184:                                 $info.':'.$grades,$homeserver);
                   9185:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9186:                 my @items = split(/&/,$response);
                   9187:                 foreach my $item (@items) {
                   9188:                     my ($key,$value) = split('=',$item);
                   9189:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9190:                 }
                   9191:             }
                   9192:         }
                   9193:     }
                   9194:     return \%exportresponse;
                   9195: }
                   9196: 
1.1172.2.68  raeburn  9197: sub check_instcode_cloning {
                   9198:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9199:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9200:         return;
                   9201:     }
                   9202:     my $canclone;
                   9203:     if (@{$code_order} > 0) {
                   9204:         my $instcoderegexp ='^';
                   9205:         my @clonecodes = split(/\&/,$cloner);
                   9206:         foreach my $item (@{$code_order}) {
                   9207:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9208:                 foreach my $pair (@clonecodes) {
                   9209:                     my ($key,$val) = split(/\=/,$pair,2);
                   9210:                     $val = &unescape($val);
                   9211:                     if ($key eq $item) {
                   9212:                         $instcoderegexp .= '('.$val.')';
                   9213:                         last;
                   9214:                     }
                   9215:                 }
                   9216:             } else {
                   9217:                 $instcoderegexp .= $codedefaults->{$item};
                   9218:             }
                   9219:         }
                   9220:         $instcoderegexp .= '$';
                   9221:         my (@from,@to);
                   9222:         eval {
                   9223:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9224:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9225:         };
                   9226:         if ((@from > 0) && (@to > 0)) {
                   9227:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9228:             if (!@diffs) {
                   9229:                 $canclone = 1;
                   9230:             }
                   9231:         }
                   9232:     }
                   9233:     return $canclone;
                   9234: }
                   9235: 
                   9236: sub default_instcode_cloning {
                   9237:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9238:     my (%codedefaults,@code_order,$canclone);
                   9239:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9240:         %codedefaults = %{$codedefaultsref};
                   9241:         @code_order = @{$codeorderref};
                   9242:     } elsif ($clonedom) {
                   9243:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9244:     }
                   9245:     if (($domdefclone) && (@code_order)) {
                   9246:         my @clonecodes = split(/\+/,$domdefclone);
                   9247:         my $instcoderegexp ='^';
                   9248:         foreach my $item (@code_order) {
                   9249:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9250:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9251:             } else {
                   9252:                 $instcoderegexp .= $codedefaults{$item};
                   9253:             }
                   9254:         }
                   9255:         $instcoderegexp .= '$';
                   9256:         my (@from,@to);
                   9257:         eval {
                   9258:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9259:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9260:         };
                   9261:         if ((@from > 0) && (@to > 0)) {
                   9262:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9263:             if (!@diffs) {
                   9264:                 $canclone = 1;
                   9265:             }
                   9266:         }
                   9267:     }
                   9268:     return $canclone;
                   9269: }
                   9270: 
1.679     raeburn  9271: # ------------------------------------------------------- Course Group routines
                   9272: 
                   9273: sub get_coursegroups {
1.809     raeburn  9274:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9275:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9276: }
                   9277: 
1.679     raeburn  9278: sub modify_coursegroup {
                   9279:     my ($cdom,$cnum,$groupsettings) = @_;
                   9280:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9281: }
                   9282: 
1.809     raeburn  9283: sub toggle_coursegroup_status {
                   9284:     my ($cdom,$cnum,$group,$action) = @_;
                   9285:     my ($from_namespace,$to_namespace);
                   9286:     if ($action eq 'delete') {
                   9287:         $from_namespace = 'coursegroups';
                   9288:         $to_namespace = 'deleted_groups';
                   9289:     } else {
                   9290:         $from_namespace = 'deleted_groups';
                   9291:         $to_namespace = 'coursegroups';
                   9292:     }
                   9293:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9294:     if (my $tmp = &error(%curr_group)) {
                   9295:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9296:         return ('read error',$tmp);
                   9297:     } else {
                   9298:         my %savedsettings = %curr_group; 
1.809     raeburn  9299:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9300:         my $deloutcome;
                   9301:         if ($result eq 'ok') {
1.809     raeburn  9302:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9303:         } else {
                   9304:             return ('write error',$result);
                   9305:         }
                   9306:         if ($deloutcome eq 'ok') {
                   9307:             return 'ok';
                   9308:         } else {
                   9309:             return ('delete error',$deloutcome);
                   9310:         }
                   9311:     }
                   9312: }
                   9313: 
1.679     raeburn  9314: sub modify_group_roles {
1.957     raeburn  9315:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9316:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9317:     my $role = 'gr/'.&escape($userprivs);
                   9318:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9319:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9320:     if ($result eq 'ok') {
                   9321:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9322:     }
1.679     raeburn  9323:     return $result;
                   9324: }
                   9325: 
                   9326: sub modify_coursegroup_membership {
                   9327:     my ($cdom,$cnum,$membership) = @_;
                   9328:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9329:     return $result;
                   9330: }
                   9331: 
1.682     raeburn  9332: sub get_active_groups {
                   9333:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9334:     my $now = time;
                   9335:     my %groups = ();
                   9336:     foreach my $key (keys(%env)) {
1.811     albertel 9337:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9338:             my ($start,$end) = split(/\./,$env{$key});
                   9339:             if (($end!=0) && ($end<$now)) { next; }
                   9340:             if (($start!=0) && ($start>$now)) { next; }
                   9341:             if ($1 eq $cdom && $2 eq $cnum) {
                   9342:                 $groups{$3} = $env{$key} ;
                   9343:             }
                   9344:         }
                   9345:     }
                   9346:     return %groups;
                   9347: }
                   9348: 
1.683     raeburn  9349: sub get_group_membership {
                   9350:     my ($cdom,$cnum,$group) = @_;
                   9351:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9352: }
                   9353: 
                   9354: sub get_users_groups {
                   9355:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9356:     my @usersgroups;
1.683     raeburn  9357:     my $cachetime=1800;
                   9358: 
                   9359:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9360:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9361:     if (defined($cached)) {
1.734     albertel 9362:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9363:     } else {  
                   9364:         $grouplist = '';
1.816     raeburn  9365:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9366:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9367:         my $access_end = $env{'course.'.$courseid.
                   9368:                               '.default_enrollment_end_date'};
                   9369:         my $now = time;
                   9370:         foreach my $key (keys(%roleshash)) {
                   9371:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9372:                 my $group = $1;
                   9373:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9374:                     my $start = $2;
                   9375:                     my $end = $1;
                   9376:                     if ($start == -1) { next; } # deleted from group
                   9377:                     if (($start!=0) && ($start>$now)) { next; }
                   9378:                     if (($end!=0) && ($end<$now)) {
                   9379:                         if ($access_end && $access_end < $now) {
                   9380:                             if ($access_end - $end < 86400) {
                   9381:                                 push(@usersgroups,$group);
1.733     raeburn  9382:                             }
                   9383:                         }
1.817     raeburn  9384:                         next;
1.733     raeburn  9385:                     }
1.817     raeburn  9386:                     push(@usersgroups,$group);
1.683     raeburn  9387:                 }
                   9388:             }
                   9389:         }
1.817     raeburn  9390:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9391:         $grouplist = join(':',@usersgroups);
                   9392:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9393:     }
1.733     raeburn  9394:     return @usersgroups;
1.683     raeburn  9395: }
                   9396: 
                   9397: sub devalidate_getgroups_cache {
                   9398:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9399:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9400: 
1.683     raeburn  9401:     my $hashid="$udom:$uname:$courseid";
                   9402:     &devalidate_cache_new('getgroups',$hashid);
                   9403: }
                   9404: 
1.12      www      9405: # ------------------------------------------------------------------ Plain Text
                   9406: 
                   9407: sub plaintext {
1.988     raeburn  9408:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9409:     if ($short =~ m{^cr/}) {
1.758     albertel 9410: 	return (split('/',$short))[-1];
                   9411:     }
1.742     raeburn  9412:     if (!defined($cid)) {
                   9413:         $cid = $env{'request.course.id'};
                   9414:     }
                   9415:     my %rolenames = (
1.1008    raeburn  9416:                       Course    => 'std',
                   9417:                       Community => 'alt1',
1.742     raeburn  9418:                     );
1.1037    raeburn  9419:     if ($cid ne '') {
                   9420:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9421:             unless ($forcedefault) {
                   9422:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9423:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9424:                 return &Apache::lonlocal::mt($roletext);
                   9425:             }
                   9426:         }
                   9427:     }
                   9428:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9429:         (defined($rolenames{$type})) && 
                   9430:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9431:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9432:     } elsif ($cid ne '') {
                   9433:         my $crstype = $env{'course.'.$cid.'.type'};
                   9434:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9435:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9436:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9437:         }
1.742     raeburn  9438:     }
1.1037    raeburn  9439:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9440: }
                   9441: 
                   9442: # ----------------------------------------------------------------- Assign Role
                   9443: 
                   9444: sub assignrole {
1.957     raeburn  9445:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9446:         $context)=@_;
1.21      www      9447:     my $mrole;
                   9448:     if ($role =~ /^cr\//) {
1.393     www      9449:         my $cwosec=$url;
1.811     albertel 9450:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9451: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9452:            my $refused = 1;
                   9453:            if ($context eq 'requestcourses') {
                   9454:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9455:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9456:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9457:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9458:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9459:                            if ($crsenv{'internal.courseowner'} eq
                   9460:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9461:                                $refused = '';
                   9462:                            }
                   9463:                        }
                   9464:                    }
                   9465:                }
                   9466:            }
                   9467:            if ($refused) {
                   9468:                &logthis('Refused custom assignrole: '.
                   9469:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9470:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9471:                return 'refused';
                   9472:            }
1.104     www      9473:         }
1.21      www      9474:         $mrole='cr';
1.678     raeburn  9475:     } elsif ($role =~ /^gr\//) {
                   9476:         my $cwogrp=$url;
1.811     albertel 9477:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9478:         unless (&allowed('mdg',$cwogrp)) {
                   9479:             &logthis('Refused group assignrole: '.
                   9480:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9481:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9482:             return 'refused';
                   9483:         }
                   9484:         $mrole='gr';
1.21      www      9485:     } else {
1.82      www      9486:         my $cwosec=$url;
1.811     albertel 9487:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9488:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9489:             my $refused;
                   9490:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9491:                 if (!(&allowed('c'.$role,$url))) {
                   9492:                     $refused = 1;
                   9493:                 }
                   9494:             } else {
                   9495:                 $refused = 1;
                   9496:             }
1.947     raeburn  9497:             if ($refused) {
1.1045    raeburn  9498:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9499:                 if (!$selfenroll && $context eq 'course') {
                   9500:                     my %crsenv;
                   9501:                     if ($role eq 'cc' || $role eq 'co') {
                   9502:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9503:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9504:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9505:                                 if ($crsenv{'internal.courseowner'} eq 
                   9506:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9507:                                     $refused = '';
                   9508:                                 }
                   9509:                             }
                   9510:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9511:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9512:                                 if ($crsenv{'internal.courseowner'} eq 
                   9513:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9514:                                     $refused = '';
                   9515:                                 }
                   9516:                             }
                   9517:                         }
                   9518:                     }
                   9519:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9520:                     $refused = '';
1.1017    raeburn  9521:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9522:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9523:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9524:                         my $wrongcc;
                   9525:                         if ($cnum =~ /^$match_community$/) {
                   9526:                             $wrongcc = 1 if ($role eq 'cc');
                   9527:                         } else {
                   9528:                             $wrongcc = 1 if ($role eq 'co');
                   9529:                         }
                   9530:                         unless ($wrongcc) {
                   9531:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9532:                             if ($crsenv{'internal.courseowner'} eq 
                   9533:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9534:                                 $refused = '';
                   9535:                             }
1.1017    raeburn  9536:                         }
                   9537:                     }
1.1172.2.9  raeburn  9538:                 } elsif ($context eq 'requestauthor') {
                   9539:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9540:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9541:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9542:                             $refused = '';
                   9543:                         } else {
                   9544:                             my %domdefaults = &get_domain_defaults($udom);
                   9545:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9546:                                 my $checkbystatus;
                   9547:                                 if ($env{'user.adv'}) {
                   9548:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9549:                                     if ($disposition eq 'automatic') {
                   9550:                                         $refused = '';
                   9551:                                     } elsif ($disposition eq '') {
                   9552:                                         $checkbystatus = 1;
                   9553:                                     }
                   9554:                                 } else {
                   9555:                                     $checkbystatus = 1;
                   9556:                                 }
                   9557:                                 if ($checkbystatus) {
                   9558:                                     if ($env{'environment.inststatus'}) {
                   9559:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9560:                                         foreach my $type (@inststatuses) {
                   9561:                                             if (($type ne '') &&
                   9562:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9563:                                                 $refused = '';
                   9564:                                             }
                   9565:                                         }
                   9566:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9567:                                         $refused = '';
                   9568:                                     }
                   9569:                                 }
                   9570:                             }
                   9571:                         }
                   9572:                     }
1.1017    raeburn  9573:                 }
                   9574:                 if ($refused) {
1.947     raeburn  9575:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9576:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9577: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9578:                     return 'refused';
                   9579:                 }
1.932     raeburn  9580:             }
1.1131    raeburn  9581:         } elsif ($role eq 'au') {
                   9582:             if ($url ne '/'.$udom.'/') {
                   9583:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9584:                          ' to assign author role for '.$uname.':'.$udom.
                   9585:                          ' in domain: '.$url.' refused (wrong domain).');
                   9586:                 return 'refused';
                   9587:             }
1.104     www      9588:         }
1.21      www      9589:         $mrole=$role;
                   9590:     }
1.620     albertel 9591:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9592:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9593:     if ($end) { $command.='_'.$end; }
1.21      www      9594:     if ($start) {
                   9595: 	if ($end) { 
1.81      www      9596:            $command.='_'.$start; 
1.21      www      9597:         } else {
1.81      www      9598:            $command.='_0_'.$start;
1.21      www      9599:         }
                   9600:     }
1.739     raeburn  9601:     my $origstart = $start;
                   9602:     my $origend = $end;
1.957     raeburn  9603:     my $delflag;
1.357     www      9604: # actually delete
                   9605:     if ($deleteflag) {
1.373     www      9606: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9607: # modify command to delete the role
1.620     albertel 9608:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9609:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9610: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9611: # set start and finish to negative values for userrolelog
                   9612:            $start=-1;
                   9613:            $end=-1;
1.957     raeburn  9614:            $delflag = 1;
1.357     www      9615:         }
                   9616:     }
                   9617: # send command
1.349     www      9618:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9619: # log new user role if status is ok
1.349     www      9620:     if ($answer eq 'ok') {
1.663     raeburn  9621: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9622:         if (($role eq 'cc') || ($role eq 'in') ||
                   9623:             ($role eq 'ep') || ($role eq 'ad') ||
                   9624:             ($role eq 'ta') || ($role eq 'st') ||
                   9625:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9626:             ($role eq 'co')) {
1.1172.2.13  raeburn  9627: # for course roles, perform group memberships changes triggered by role change.
                   9628:             unless ($role =~ /^gr/) {
                   9629:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9630:                                                  $origstart,$selfenroll,$context);
                   9631:             }
1.1172.2.9  raeburn  9632:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9633:                            $selfenroll,$context);
                   9634:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9635:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9636:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9637:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9638:                            $context);
                   9639:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9640:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9641:                              $context);
                   9642:         }
1.1053    raeburn  9643:         if ($role eq 'cc') {
                   9644:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9645:         }
1.349     www      9646:     }
                   9647:     return $answer;
1.169     harris41 9648: }
                   9649: 
1.1053    raeburn  9650: sub autoupdate_coowners {
                   9651:     my ($url,$end,$start,$uname,$udom) = @_;
                   9652:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9653:     if (($cdom ne '') && ($cnum ne '')) {
                   9654:         my $now = time;
                   9655:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9656:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9657:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9658:             my $instcode = $coursehash{'internal.coursecode'};
                   9659:             if ($instcode ne '') {
1.1056    raeburn  9660:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9661:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9662:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9663:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9664:                         if ($result eq 'valid') {
                   9665:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9666:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9667:                                     push(@newcoowners,$coowner);
                   9668:                                 }
                   9669:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9670:                                     push(@newcoowners,$uname.':'.$udom);
                   9671:                                 }
                   9672:                                 @newcoowners = sort(@newcoowners);
                   9673:                             } else {
                   9674:                                 push(@newcoowners,$uname.':'.$udom);
                   9675:                             }
                   9676:                         } else {
                   9677:                             if ($coursehash{'internal.co-owners'}) {
                   9678:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9679:                                     unless ($coowner eq $uname.':'.$udom) {
                   9680:                                         push(@newcoowners,$coowner);
                   9681:                                     }
                   9682:                                 }
                   9683:                                 unless (@newcoowners > 0) {
                   9684:                                     $delcoowners = 1;
                   9685:                                     $coowners = '';
                   9686:                                 }
                   9687:                             }
                   9688:                         }
                   9689:                         if (@newcoowners || $delcoowners) {
                   9690:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9691:                                             $delcoowners,@newcoowners);
                   9692:                         }
                   9693:                     }
                   9694:                 }
                   9695:             }
                   9696:         }
                   9697:     }
                   9698: }
                   9699: 
                   9700: sub store_coowners {
                   9701:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9702:     my $cid = $cdom.'_'.$cnum;
                   9703:     my ($coowners,$delresult,$putresult);
                   9704:     if (@newcoowners) {
                   9705:         $coowners = join(',',@newcoowners);
                   9706:         my %coownershash = (
                   9707:                             'internal.co-owners' => $coowners,
                   9708:                            );
                   9709:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9710:         if ($putresult eq 'ok') {
                   9711:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9712:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9713:             }
                   9714:         }
                   9715:     }
                   9716:     if ($delcoowners) {
                   9717:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9718:         if ($delresult eq 'ok') {
                   9719:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9720:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9721:             }
                   9722:         }
                   9723:     }
                   9724:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9725:         my %crsinfo =
                   9726:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9727:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9728:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9729:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9730:         }
                   9731:     }
                   9732: }
                   9733: 
1.169     harris41 9734: # -------------------------------------------------- Modify user authentication
1.197     www      9735: # Overrides without validation
                   9736: 
1.169     harris41 9737: sub modifyuserauth {
                   9738:     my ($udom,$uname,$umode,$upass)=@_;
                   9739:     my $uhome=&homeserver($uname,$udom);
1.197     www      9740:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9741:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9742:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9743:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9744:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9745: 		     &escape($upass),$uhome);
1.620     albertel 9746:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9747:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9748:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9749:     &log($udom,,$uname,$uhome,
1.620     albertel 9750:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9751:                                      $env{'user.name'}.', '.$umode.
1.197     www      9752:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9753:     unless ($reply eq 'ok') {
1.197     www      9754:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9755: 	return 'error: '.$reply;
                   9756:     }   
1.170     harris41 9757:     return 'ok';
1.80      www      9758: }
                   9759: 
1.81      www      9760: # --------------------------------------------------------------- Modify a user
1.80      www      9761: 
1.81      www      9762: sub modifyuser {
1.206     matthew  9763:     my ($udom,    $uname, $uid,
                   9764:         $umode,   $upass, $first,
                   9765:         $middle,  $last,  $gene,
1.1058    raeburn  9766:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9767:     $udom= &LONCAPA::clean_domain($udom);
                   9768:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9769:     my $showcandelete = 'none';
                   9770:     if (ref($candelete) eq 'ARRAY') {
                   9771:         if (@{$candelete} > 0) {
                   9772:             $showcandelete = join(', ',@{$candelete});
                   9773:         }
                   9774:     }
1.81      www      9775:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9776:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9777: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9778:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9779:                                      ' desiredhome not specified'). 
1.620     albertel 9780:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9781:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9782:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9783:     my $newuser;
                   9784:     if ($uhome eq 'no_host') {
                   9785:         $newuser = 1;
                   9786:     }
1.80      www      9787: # ----------------------------------------------------------------- Create User
1.406     albertel 9788:     if (($uhome eq 'no_host') && 
                   9789: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9790:         my $unhome='';
1.844     albertel 9791:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9792:             $unhome = $desiredhome;
1.620     albertel 9793: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9794: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9795:         } else { # load balancing routine for determining $unhome
1.81      www      9796:             my $loadm=10000000;
1.841     albertel 9797: 	    my %servers = &get_servers($udom,'library');
                   9798: 	    foreach my $tryserver (keys(%servers)) {
                   9799: 		my $answer=reply('load',$tryserver);
                   9800: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9801: 		    $loadm=$answer;
                   9802: 		    $unhome=$tryserver;
                   9803: 		}
1.80      www      9804: 	    }
                   9805:         }
                   9806:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9807: 	    return 'error: unable to find a home server for '.$uname.
                   9808:                    ' in domain '.$udom;
1.80      www      9809:         }
                   9810:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9811:                          &escape($upass),$unhome);
                   9812: 	unless ($reply eq 'ok') {
                   9813:             return 'error: '.$reply;
                   9814:         }   
1.230     stredwic 9815:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9816:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9817: 	    return 'error: unable verify users home machine.';
1.80      www      9818:         }
1.209     matthew  9819:     }   # End of creation of new user
1.80      www      9820: # ---------------------------------------------------------------------- Add ID
                   9821:     if ($uid) {
                   9822:        $uid=~tr/A-Z/a-z/;
                   9823:        my %uidhash=&idrget($udom,$uname);
1.196     www      9824:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9825:          && (!$forceid)) {
1.80      www      9826: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9827: 	      return 'error: user id "'.$uid.'" does not match '.
                   9828:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9829:           }
                   9830:        } else {
                   9831: 	  &idput($udom,($uname => $uid));
                   9832:        }
                   9833:     }
                   9834: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9835:     my @tmp=&get('environment',
1.899     raeburn  9836: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9837:                     'permanentemail','inststatus'],
1.134     albertel 9838: 		   $udom,$uname);
1.1075    raeburn  9839:     my (%names,%oldnames);
1.313     matthew  9840:     if ($tmp[0] =~ m/^error:.*/) { 
                   9841:         %names=(); 
                   9842:     } else {
                   9843:         %names = @tmp;
1.1075    raeburn  9844:         %oldnames = %names;
1.313     matthew  9845:     }
1.388     www      9846: #
1.1058    raeburn  9847: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9848: # of users did not contain them), do not overwrite existing values
                   9849: # unless field is in $candelete array ref.  
                   9850: #
                   9851: 
                   9852:     my @fields = ('firstname','middlename','lastname','generation',
                   9853:                   'permanentemail','id');
                   9854:     my %newvalues;
                   9855:     if (ref($candelete) eq 'ARRAY') {
                   9856:         foreach my $field (@fields) {
                   9857:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9858:                 if ($field eq 'firstname') {
                   9859:                     $names{$field} = $first;
                   9860:                 } elsif ($field eq 'middlename') {
                   9861:                     $names{$field} = $middle;
                   9862:                 } elsif ($field eq 'lastname') {
                   9863:                     $names{$field} = $last;
                   9864:                 } elsif ($field eq 'generation') { 
                   9865:                     $names{$field} = $gene;
                   9866:                 } elsif ($field eq 'permanentemail') {
                   9867:                     $names{$field} = $email;
                   9868:                 } elsif ($field eq 'id') {
                   9869:                     $names{$field}  = $uid;
                   9870:                 }
                   9871:             }
                   9872:         }
                   9873:     }
1.388     www      9874:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9875:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9876:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9877:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9878:     if ($email) {
                   9879:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9880:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9881:     }
1.899     raeburn  9882:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9883:     if (defined($inststatus)) {
                   9884:         $names{'inststatus'} = '';
                   9885:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9886:         if (ref($usertypes) eq 'HASH') {
                   9887:             my @okstatuses; 
                   9888:             foreach my $item (split(/:/,$inststatus)) {
                   9889:                 if (defined($usertypes->{$item})) {
                   9890:                     push(@okstatuses,$item);  
                   9891:                 }
                   9892:             }
                   9893:             if (@okstatuses) {
                   9894:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9895:             }
                   9896:         }
                   9897:     }
1.1075    raeburn  9898:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9899:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9900:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9901:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9902:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9903:     } else {
                   9904:         $logmsg .= ' during self creation';
                   9905:     }
1.1075    raeburn  9906:     my $changed;
                   9907:     if ($newuser) {
                   9908:         $changed = 1;
                   9909:     } else {
                   9910:         foreach my $field (@fields) {
                   9911:             if ($names{$field} ne $oldnames{$field}) {
                   9912:                 $changed = 1;
                   9913:                 last;
                   9914:             }
                   9915:         }
                   9916:     }
                   9917:     unless ($changed) {
                   9918:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9919:         &logthis($logmsg);
                   9920:         return 'ok';
                   9921:     }
                   9922:     my $reply = &put('environment', \%names, $udom,$uname);
                   9923:     if ($reply ne 'ok') { 
                   9924:         return 'error: '.$reply;
                   9925:     }
1.1087    raeburn  9926:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9927:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9928:     }
1.1075    raeburn  9929:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9930:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9931:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9932:     &logthis($logmsg);
1.134     albertel 9933:     return 'ok';
1.80      www      9934: }
                   9935: 
1.81      www      9936: # -------------------------------------------------------------- Modify student
1.80      www      9937: 
1.81      www      9938: sub modifystudent {
                   9939:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9940:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  9941:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9942:     if (!$cid) {
1.620     albertel 9943: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9944: 	    return 'not_in_class';
                   9945: 	}
1.80      www      9946:     }
                   9947: # --------------------------------------------------------------- Make the user
1.81      www      9948:     my $reply=&modifyuser
1.209     matthew  9949: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9950:          $desiredhome,$email,$inststatus);
1.80      www      9951:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9952:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  9953:     # student's environment
1.297     matthew  9954:     $uid = undef if (!$forceid);
1.455     albertel 9955:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  9956: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  9957:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9958:     return $reply;
                   9959: }
                   9960: 
                   9961: sub modify_student_enrollment {
1.1172.2.23  raeburn  9962:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  9963:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9964:     my ($cdom,$cnum,$chome);
                   9965:     if (!$cid) {
1.620     albertel 9966: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9967: 	    return 'not_in_class';
                   9968: 	}
1.620     albertel 9969: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9970: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9971:     } else {
                   9972: 	($cdom,$cnum)=split(/_/,$cid);
                   9973:     }
1.620     albertel 9974:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9975:     if (!$chome) {
1.457     raeburn  9976: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9977:     }
1.455     albertel 9978:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9979:     # Make sure the user exists
1.81      www      9980:     my $uhome=&homeserver($uname,$udom);
                   9981:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9982: 	return 'error: no such user';
                   9983:     }
1.297     matthew  9984:     # Get student data if we were not given enough information
                   9985:     if (!defined($first)  || $first  eq '' || 
                   9986:         !defined($last)   || $last   eq '' || 
                   9987:         !defined($uid)    || $uid    eq '' || 
                   9988:         !defined($middle) || $middle eq '' || 
                   9989:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9990:         # They did not supply us with enough data to enroll the student, so
                   9991:         # we need to pick up more information.
1.297     matthew  9992:         my %tmp = &get('environment',
1.294     matthew  9993:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9994:                        ,$udom,$uname);
                   9995: 
1.800     albertel 9996:         #foreach my $key (keys(%tmp)) {
                   9997:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9998:         #}
1.294     matthew  9999:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10000:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10001:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10002:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10003:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10004:     }
1.556     albertel 10005:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10006:     my $user = "$uname:$udom";
                   10007:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10008:     my $reply=cput('classlist',
1.1148    raeburn  10009: 		   {$user => 
1.1172.2.76  raeburn  10010: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10011: 		   $cdom,$cnum);
1.1148    raeburn  10012:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10013:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10014:     } else { 
1.81      www      10015: 	return 'error: '.$reply;
                   10016:     }
1.297     matthew  10017:     # Add student role to user
1.83      www      10018:     my $uurl='/'.$cid;
1.81      www      10019:     $uurl=~s/\_/\//g;
                   10020:     if ($usec) {
                   10021: 	$uurl.='/'.$usec;
                   10022:     }
1.1148    raeburn  10023:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10024:                              $selfenroll,$context);
                   10025:     if ($result ne 'ok') {
                   10026:         if ($old_entry{$user} ne '') {
                   10027:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10028:         } else {
                   10029:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10030:         }
                   10031:     }
                   10032:     return $result; 
1.21      www      10033: }
                   10034: 
1.556     albertel 10035: sub format_name {
                   10036:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10037:     my $name;
                   10038:     if ($first ne 'lastname') {
                   10039: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10040:     } else {
                   10041: 	if ($lastname=~/\S/) {
                   10042: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10043: 	    $name=~s/\s+,/,/;
                   10044: 	} else {
                   10045: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10046: 	}
                   10047:     }
                   10048:     $name=~s/^\s+//;
                   10049:     $name=~s/\s+$//;
                   10050:     $name=~s/\s+/ /g;
                   10051:     return $name;
                   10052: }
                   10053: 
1.84      www      10054: # ------------------------------------------------- Write to course preferences
                   10055: 
                   10056: sub writecoursepref {
                   10057:     my ($courseid,%prefs)=@_;
                   10058:     $courseid=~s/^\///;
                   10059:     $courseid=~s/\_/\//g;
                   10060:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10061:     my $chome=homeserver($cnum,$cdomain);
                   10062:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10063: 	return 'error: no such course';
                   10064:     }
                   10065:     my $cstring='';
1.800     albertel 10066:     foreach my $pref (keys(%prefs)) {
                   10067: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10068:     }
1.84      www      10069:     $cstring=~s/\&$//;
                   10070:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10071: }
                   10072: 
                   10073: # ---------------------------------------------------------- Make/modify course
                   10074: 
                   10075: sub createcourse {
1.741     raeburn  10076:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10077:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10078:     $url=&declutter($url);
                   10079:     my $cid='';
1.1028    raeburn  10080:     if ($context eq 'requestcourses') {
                   10081:         my $can_create = 0;
                   10082:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10083:         if ($udom eq $ownerdom) {
                   10084:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10085:                                   $context)) {
                   10086:                 $can_create = 1;
                   10087:             }
                   10088:         } else {
                   10089:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10090:                                            $category);
                   10091:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10092:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10093:                 if (@curr > 0) {
                   10094:                     my @options = qw(approval validate autolimit);
                   10095:                     my $optregex = join('|',@options);
                   10096:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10097:                         $can_create = 1;
                   10098:                     }
                   10099:                 }
                   10100:             }
                   10101:         }
                   10102:         if ($can_create) {
                   10103:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10104:                 unless (&allowed('ccc',$udom)) {
                   10105:                     return 'refused'; 
                   10106:                 }
1.1017    raeburn  10107:             }
                   10108:         } else {
                   10109:             return 'refused';
                   10110:         }
1.1028    raeburn  10111:     } elsif (!&allowed('ccc',$udom)) {
                   10112:         return 'refused';
1.84      www      10113:     }
1.1011    raeburn  10114: # --------------------------------------------------------------- Get Unique ID
                   10115:     my $uname;
                   10116:     if ($cnum =~ /^$match_courseid$/) {
                   10117:         my $chome=&homeserver($cnum,$udom,'true');
                   10118:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10119:             $uname = $cnum;
                   10120:         } else {
1.1038    raeburn  10121:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10122:         }
                   10123:     } else {
1.1038    raeburn  10124:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10125:     }
                   10126:     return $uname if ($uname =~ /^error/);
                   10127: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10128:     if (!defined($course_server)) {
                   10129:         if (defined(&domain($udom,'primary'))) {
                   10130:             $course_server = &domain($udom,'primary');
                   10131:         } else {
                   10132:             $course_server = $env{'user.home'}; 
                   10133:         }
                   10134:     }
                   10135:     my %host_servers =
                   10136:         &Apache::lonnet::get_servers($udom,'library');
                   10137:     unless ($host_servers{$course_server}) {
                   10138:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10139:     }
1.84      www      10140: # ------------------------------------------------------------- Make the course
                   10141:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10142:                       $course_server);
1.84      www      10143:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10144:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10145:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10146: 	return 'error: no such course';
                   10147:     }
1.271     www      10148: # ----------------------------------------------------------------- Course made
1.516     raeburn  10149: # log existence
1.1029    raeburn  10150:     my $now = time;
1.918     raeburn  10151:     my $newcourse = {
                   10152:                     $udom.'_'.$uname => {
1.921     raeburn  10153:                                      description => $description,
                   10154:                                      inst_code   => $inst_code,
                   10155:                                      owner       => $course_owner,
                   10156:                                      type        => $crstype,
1.1029    raeburn  10157:                                      creator     => $env{'user.name'}.':'.
                   10158:                                                     $env{'user.domain'},
                   10159:                                      created     => $now,
                   10160:                                      context     => $context,
1.918     raeburn  10161:                                                 },
                   10162:                     };
1.921     raeburn  10163:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10164: # set toplevel url
1.271     www      10165:     my $topurl=$url;
                   10166:     unless ($nonstandard) {
                   10167: # ------------------------------------------ For standard courses, make top url
                   10168:         my $mapurl=&clutter($url);
1.278     www      10169:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10170:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10171: <map>
                   10172: <resource id="1" type="start"></resource>
                   10173: <resource id="2" src="$mapurl"></resource>
                   10174: <resource id="3" type="finish"></resource>
                   10175: <link index="1" from="1" to="2"></link>
                   10176: <link index="2" from="2" to="3"></link>
                   10177: </map>
                   10178: ENDINITMAP
                   10179:         $topurl=&declutter(
1.638     albertel 10180:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10181:                           );
                   10182:     }
                   10183: # ----------------------------------------------------------- Write preferences
1.84      www      10184:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10185:                      ('description'              => $description,
                   10186:                       'url'                      => $topurl,
                   10187:                       'internal.creator'         => $env{'user.name'}.':'.
                   10188:                                                     $env{'user.domain'},
                   10189:                       'internal.created'         => $now,
                   10190:                       'internal.creationcontext' => $context)
                   10191:                     );
1.84      www      10192:     return '/'.$udom.'/'.$uname;
                   10193: }
                   10194: 
1.1011    raeburn  10195: # ------------------------------------------------------------------- Create ID
                   10196: sub generate_coursenum {
1.1038    raeburn  10197:     my ($udom,$crstype) = @_;
1.1011    raeburn  10198:     my $domdesc = &domain($udom);
                   10199:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10200:     my $first;
                   10201:     if ($crstype eq 'Community') {
                   10202:         $first = '0';
                   10203:     } else {
                   10204:         $first = int(1+rand(9)); 
                   10205:     } 
                   10206:     my $uname=$first.
1.1011    raeburn  10207:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10208:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10209:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10210: # ----------------------------------------------- Make sure that does not exist
                   10211:     my $uhome=&homeserver($uname,$udom,'true');
                   10212:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10213:         if ($crstype eq 'Community') {
                   10214:             $first = '0';
                   10215:         } else {
                   10216:             $first = int(1+rand(9));
                   10217:         }
                   10218:         $uname=$first.
1.1011    raeburn  10219:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10220:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10221:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10222:         $uhome=&homeserver($uname,$udom,'true');
                   10223:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10224:             return 'error: unable to generate unique course-ID';
                   10225:         }
                   10226:     }
                   10227:     return $uname;
                   10228: }
                   10229: 
1.813     albertel 10230: sub is_course {
1.1167    droeschl 10231:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10232:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10233:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10234:     my $uhome=&homeserver($cnum,$cdom);
                   10235:     my $iscourse;
                   10236:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10237:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10238:     } else {
                   10239:         my $hashid = $cdom.':'.$cnum;
                   10240:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10241:         unless (defined($cached)) {
                   10242:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10243:                                         $cnum,undef,undef,'.');
                   10244:             $iscourse = 0;
                   10245:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10246:                 $iscourse = 1;
                   10247:             }
                   10248:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10249:         }
                   10250:     }
                   10251:     return unless($iscourse);
1.1167    droeschl 10252:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10253: }
                   10254: 
1.1015    raeburn  10255: sub store_userdata {
                   10256:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10257:     my $result;
1.1016    raeburn  10258:     if ($datakey ne '') {
1.1013    raeburn  10259:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10260:             if ($udom eq '' || $uname eq '') {
                   10261:                 $udom = $env{'user.domain'};
                   10262:                 $uname = $env{'user.name'};
                   10263:             }
                   10264:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10265:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10266:                 $result = 'error: no_host';
                   10267:             } else {
                   10268:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10269:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10270: 
                   10271:                 my $namevalue='';
                   10272:                 foreach my $key (keys(%{$storehash})) {
                   10273:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10274:                 }
                   10275:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10276:                 unless ($namespace eq 'courserequests') {
                   10277:                     $datakey = &escape($datakey);
                   10278:                 }
1.1105    raeburn  10279:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10280:                                   $namevalue,$uhome);
1.1013    raeburn  10281:             }
                   10282:         } else {
                   10283:             $result = 'error: data to store was not a hash reference'; 
                   10284:         }
                   10285:     } else {
                   10286:         $result= 'error: invalid requestkey'; 
                   10287:     }
                   10288:     return $result;
                   10289: }
                   10290: 
1.21      www      10291: # ---------------------------------------------------------- Assign Custom Role
                   10292: 
                   10293: sub assigncustomrole {
1.957     raeburn  10294:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10295:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10296:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10297: }
                   10298: 
                   10299: # ----------------------------------------------------------------- Revoke Role
                   10300: 
                   10301: sub revokerole {
1.957     raeburn  10302:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10303:     my $now=time;
1.965     raeburn  10304:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10305: }
                   10306: 
                   10307: # ---------------------------------------------------------- Revoke Custom Role
                   10308: 
                   10309: sub revokecustomrole {
1.957     raeburn  10310:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10311:     my $now=time;
1.357     www      10312:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10313:            $deleteflag,$selfenroll,$context);
1.17      www      10314: }
                   10315: 
1.533     banghart 10316: # ------------------------------------------------------------ Disk usage
1.535     albertel 10317: sub diskusage {
1.955     raeburn  10318:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10319:     $directorypath =~ s/\/$//;
                   10320:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10321:                        .&escape($getpropath).':'.&escape($uname).':'
                   10322:                        .&escape($udom),homeserver($uname,$udom));
                   10323:     if ($listing eq 'unknown_cmd') {
                   10324:         if ($getpropath) {
                   10325:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10326:         }
                   10327:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10328:     }
1.514     albertel 10329:     return $listing;
1.512     banghart 10330: }
                   10331: 
1.566     banghart 10332: sub is_locked {
1.1096    raeburn  10333:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10334:     my @check;
                   10335:     my $is_locked;
1.1093    raeburn  10336:     push (@check,$file_name);
1.613     albertel 10337:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10338: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10339:     my ($tmp)=keys(%locked);
                   10340:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10341:     
1.566     banghart 10342:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10343:         $is_locked = 'false';
                   10344:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10345:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10346:                $is_locked = 'true';
1.1096    raeburn  10347:                if (ref($which) eq 'ARRAY') {
                   10348:                    push(@{$which},$entry);
                   10349:                } else {
                   10350:                    last;
                   10351:                }
1.745     raeburn  10352:            }
                   10353:        }
1.566     banghart 10354:     } else {
                   10355:         $is_locked = 'false';
                   10356:     }
1.1093    raeburn  10357:     return $is_locked;
1.566     banghart 10358: }
                   10359: 
1.759     albertel 10360: sub declutter_portfile {
                   10361:     my ($file) = @_;
1.833     albertel 10362:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10363:     return $file;
                   10364: }
                   10365: 
1.559     banghart 10366: # ------------------------------------------------------------- Mark as Read Only
                   10367: 
                   10368: sub mark_as_readonly {
                   10369:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10370:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10371:     my ($tmp)=keys(%current_permissions);
                   10372:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10373:     foreach my $file (@{$files}) {
1.759     albertel 10374: 	$file = &declutter_portfile($file);
1.561     banghart 10375:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10376:     }
1.613     albertel 10377:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10378:     return;
                   10379: }
                   10380: 
1.572     banghart 10381: # ------------------------------------------------------------Save Selected Files
                   10382: 
                   10383: sub save_selected_files {
                   10384:     my ($user, $path, @files) = @_;
                   10385:     my $filename = $user."savedfiles";
1.573     banghart 10386:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10387:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10388:     foreach my $file (@files) {
1.620     albertel 10389:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10390:     }
                   10391:     foreach my $file (@other_files) {
1.574     banghart 10392:         print (OUT $file."\n");
1.572     banghart 10393:     }
1.574     banghart 10394:     close (OUT);
1.572     banghart 10395:     return 'ok';
                   10396: }
                   10397: 
1.574     banghart 10398: sub clear_selected_files {
                   10399:     my ($user) = @_;
                   10400:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10401:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10402:     print (OUT undef);
                   10403:     close (OUT);
                   10404:     return ("ok");    
                   10405: }
                   10406: 
1.572     banghart 10407: sub files_in_path {
                   10408:     my ($user, $path) = @_;
                   10409:     my $filename = $user."savedfiles";
                   10410:     my %return_files;
1.1172.2.96  raeburn  10411:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10412:     while (my $line_in = <IN>) {
1.574     banghart 10413:         chomp ($line_in);
                   10414:         my @paths_and_file = split (m!/!, $line_in);
                   10415:         my $file_part = pop (@paths_and_file);
                   10416:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10417:         $path_part.='/';
                   10418:         my $path_and_file = $path_part.$file_part;
                   10419:         if ($path_part eq $path) {
                   10420:             $return_files{$file_part}= 'selected';
                   10421:         }
                   10422:     }
1.574     banghart 10423:     close (IN);
                   10424:     return (\%return_files);
1.572     banghart 10425: }
                   10426: 
                   10427: # called in portfolio select mode, to show files selected NOT in current directory
                   10428: sub files_not_in_path {
                   10429:     my ($user, $path) = @_;
                   10430:     my $filename = $user."savedfiles";
                   10431:     my @return_files;
                   10432:     my $path_part;
1.1172.2.96  raeburn  10433:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10434:     while (my $line = <IN>) {
1.572     banghart 10435:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10436:         my @paths_and_file = split(m|/|, $line);
                   10437:         my $file_part = pop(@paths_and_file);
                   10438:         chomp($file_part);
                   10439:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10440:         $path_part .= '/';
                   10441:         my $path_and_file = $path_part.$file_part;
                   10442:         if ($path_part ne $path) {
1.800     albertel 10443:             push(@return_files, ($path_and_file));
1.572     banghart 10444:         }
                   10445:     }
1.800     albertel 10446:     close(OUT);
1.574     banghart 10447:     return (@return_files);
1.572     banghart 10448: }
                   10449: 
1.745     raeburn  10450: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10451: 
1.745     raeburn  10452: sub get_portfile_permissions {
                   10453:     my ($domain,$user) = @_;
1.613     albertel 10454:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10455:     my ($tmp)=keys(%current_permissions);
                   10456:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10457:     return \%current_permissions;
                   10458: }
                   10459: 
                   10460: #---------------------------------------------Get portfolio file access controls
                   10461: 
1.749     raeburn  10462: sub get_access_controls {
1.745     raeburn  10463:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10464:     my %access;
                   10465:     my $real_file = $file;
                   10466:     $file =~ s/\.meta$//;
1.745     raeburn  10467:     if (defined($file)) {
1.749     raeburn  10468:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10469:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10470:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10471:             }
                   10472:         }
1.745     raeburn  10473:     } else {
1.749     raeburn  10474:         foreach my $key (keys(%{$current_permissions})) {
                   10475:             if ($key =~ /\0accesscontrol$/) {
                   10476:                 if (defined($group)) {
                   10477:                     if ($key !~ m-^\Q$group\E/-) {
                   10478:                         next;
                   10479:                     }
                   10480:                 }
                   10481:                 my ($fullpath) = split(/\0/,$key);
                   10482:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10483:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10484:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10485:                     }
                   10486:                 }
                   10487:             }
                   10488:         }
                   10489:     }
                   10490:     return %access;
                   10491: }
                   10492: 
                   10493: sub modify_access_controls {
                   10494:     my ($file_name,$changes,$domain,$user)=@_;
                   10495:     my ($outcome,$deloutcome);
                   10496:     my %store_permissions;
                   10497:     my %new_values;
                   10498:     my %new_control;
                   10499:     my %translation;
                   10500:     my @deletions = ();
                   10501:     my $now = time;
                   10502:     if (exists($$changes{'activate'})) {
                   10503:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10504:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10505:             my $numnew = scalar(@newitems);
                   10506:             for (my $i=0; $i<$numnew; $i++) {
                   10507:                 my $newkey = $newitems[$i];
                   10508:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10509:                 if ($newkey =~ /^\d+:/) { 
                   10510:                     $newkey =~ s/^(\d+)/$newid/;
                   10511:                     $translation{$1} = $newid;
                   10512:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10513:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10514:                     $translation{$1} = $newid;
                   10515:                 }
1.749     raeburn  10516:                 $new_values{$file_name."\0".$newkey} = 
                   10517:                                           $$changes{'activate'}{$newitems[$i]};
                   10518:                 $new_control{$newkey} = $now;
                   10519:             }
                   10520:         }
                   10521:     }
                   10522:     my %todelete;
                   10523:     my %changed_items;
                   10524:     foreach my $action ('delete','update') {
                   10525:         if (exists($$changes{$action})) {
                   10526:             if (ref($$changes{$action}) eq 'HASH') {
                   10527:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10528:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10529:                     if ($action eq 'delete') { 
                   10530:                         $todelete{$itemnum} = 1;
                   10531:                     } else {
                   10532:                         $changed_items{$itemnum} = $key;
                   10533:                     }
                   10534:                 }
1.745     raeburn  10535:             }
                   10536:         }
1.749     raeburn  10537:     }
                   10538:     # get lock on access controls for file.
                   10539:     my $lockhash = {
                   10540:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10541:                                                        ':'.$env{'user.domain'},
                   10542:                    }; 
                   10543:     my $tries = 0;
                   10544:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10545:    
1.1172.2.79  raeburn  10546:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10547:         $tries ++;
1.1172.2.79  raeburn  10548:         sleep(0.1);
1.749     raeburn  10549:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10550:     }
                   10551:     if ($gotlock eq 'ok') {
                   10552:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10553:         my ($tmp)=keys(%curr_permissions);
                   10554:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10555:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10556:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10557:             if (ref($curr_controls) eq 'HASH') {
                   10558:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10559:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10560:                     if (defined($todelete{$itemnum})) {
                   10561:                         push(@deletions,$file_name."\0".$control_item);
                   10562:                     } else {
                   10563:                         if (defined($changed_items{$itemnum})) {
                   10564:                             $new_control{$changed_items{$itemnum}} = $now;
                   10565:                             push(@deletions,$file_name."\0".$control_item);
                   10566:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10567:                         } else {
                   10568:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10569:                         }
                   10570:                     }
1.745     raeburn  10571:                 }
                   10572:             }
                   10573:         }
1.970     raeburn  10574:         my ($group);
                   10575:         if (&is_course($domain,$user)) {
                   10576:             ($group,my $file) = split(/\//,$file_name,2);
                   10577:         }
1.749     raeburn  10578:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10579:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10580:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10581:         #  remove lock
                   10582:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10583:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10584:         my $sqlresult =
1.970     raeburn  10585:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10586:                                     $group);
1.749     raeburn  10587:     } else {
                   10588:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10589:     }
1.749     raeburn  10590:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10591: }
                   10592: 
1.827     raeburn  10593: sub make_public_indefinitely {
                   10594:     my ($requrl) = @_;
                   10595:     my $now = time;
                   10596:     my $action = 'activate';
                   10597:     my $aclnum = 0;
                   10598:     if (&is_portfolio_url($requrl)) {
                   10599:         my (undef,$udom,$unum,$file_name,$group) =
                   10600:             &parse_portfolio_url($requrl);
                   10601:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10602:         my %access_controls = &get_access_controls($current_perms,
                   10603:                                                    $group,$file_name);
                   10604:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10605:             my ($num,$scope,$end,$start) = 
                   10606:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10607:             if ($scope eq 'public') {
                   10608:                 if ($start <= $now && $end == 0) {
                   10609:                     $action = 'none';
                   10610:                 } else {
                   10611:                     $action = 'update';
                   10612:                     $aclnum = $num;
                   10613:                 }
                   10614:                 last;
                   10615:             }
                   10616:         }
                   10617:         if ($action eq 'none') {
                   10618:              return 'ok';
                   10619:         } else {
                   10620:             my %changes;
                   10621:             my $newend = 0;
                   10622:             my $newstart = $now;
                   10623:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10624:             $changes{$action}{$newkey} = {
                   10625:                 type => 'public',
                   10626:                 time => {
                   10627:                     start => $newstart,
                   10628:                     end   => $newend,
                   10629:                 },
                   10630:             };
                   10631:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10632:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10633:             return $outcome;
                   10634:         }
                   10635:     } else {
                   10636:         return 'invalid';
                   10637:     }
                   10638: }
                   10639: 
1.745     raeburn  10640: #------------------------------------------------------Get Marked as Read Only
                   10641: 
                   10642: sub get_marked_as_readonly {
                   10643:     my ($domain,$user,$what,$group) = @_;
                   10644:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10645:     my @readonly_files;
1.629     banghart 10646:     my $cmp1=$what;
                   10647:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10648:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10649:         if (defined($group)) {
                   10650:             if ($file_name !~ m-^\Q$group\E/-) {
                   10651:                 next;
                   10652:             }
                   10653:         }
1.561     banghart 10654:         if (ref($value) eq "ARRAY"){
                   10655:             foreach my $stored_what (@{$value}) {
1.629     banghart 10656:                 my $cmp2=$stored_what;
1.759     albertel 10657:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10658:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10659:                 }
1.629     banghart 10660:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10661:                     push(@readonly_files, $file_name);
1.745     raeburn  10662:                     last;
1.563     banghart 10663:                 } elsif (!defined($what)) {
                   10664:                     push(@readonly_files, $file_name);
1.745     raeburn  10665:                     last;
1.561     banghart 10666:                 }
                   10667:             }
1.745     raeburn  10668:         }
1.561     banghart 10669:     }
                   10670:     return @readonly_files;
                   10671: }
1.577     banghart 10672: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10673: 
1.577     banghart 10674: sub get_marked_as_readonly_hash {
1.745     raeburn  10675:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10676:     my %readonly_files;
1.745     raeburn  10677:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10678:         if (defined($group)) {
                   10679:             if ($file_name !~ m-^\Q$group\E/-) {
                   10680:                 next;
                   10681:             }
                   10682:         }
1.577     banghart 10683:         if (ref($value) eq "ARRAY"){
                   10684:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10685:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10686:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10687:                         if ($lock_descriptor eq 'graded') {
                   10688:                             $readonly_files{$file_name} = 'graded';
                   10689:                         } elsif ($lock_descriptor eq 'handback') {
                   10690:                             $readonly_files{$file_name} = 'handback';
                   10691:                         } else {
                   10692:                             if (!exists($readonly_files{$file_name})) {
                   10693:                                 $readonly_files{$file_name} = 'locked';
                   10694:                             }
                   10695:                         }
1.745     raeburn  10696:                     }
1.750     banghart 10697:                 } 
1.577     banghart 10698:             }
                   10699:         } 
                   10700:     }
                   10701:     return %readonly_files;
                   10702: }
1.559     banghart 10703: # ------------------------------------------------------------ Unmark as Read Only
                   10704: 
                   10705: sub unmark_as_readonly {
1.629     banghart 10706:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10707:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10708:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10709:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10710:     my $symb_crs = $what;
                   10711:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10712:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10713:     my ($tmp)=keys(%current_permissions);
                   10714:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10715:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10716:     foreach my $file (@readonly_files) {
1.759     albertel 10717: 	my $clean_file = &declutter_portfile($file);
                   10718: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10719: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10720:         my @new_locks;
                   10721:         my @del_keys;
                   10722:         if (ref($current_locks) eq "ARRAY"){
                   10723:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10724:                 my $compare=$locker;
1.749     raeburn  10725:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10726:                     $compare=join('',@{$locker});
1.746     raeburn  10727:                     if ($compare ne $symb_crs) {
                   10728:                         push(@new_locks, $locker);
                   10729:                     }
1.563     banghart 10730:                 }
                   10731:             }
1.650     albertel 10732:             if (scalar(@new_locks) > 0) {
1.563     banghart 10733:                 $current_permissions{$file} = \@new_locks;
                   10734:             } else {
                   10735:                 push(@del_keys, $file);
1.613     albertel 10736:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10737:                 delete($current_permissions{$file});
1.563     banghart 10738:             }
                   10739:         }
1.561     banghart 10740:     }
1.613     albertel 10741:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10742:     return;
                   10743: }
1.512     banghart 10744: 
1.17      www      10745: # ------------------------------------------------------------ Directory lister
                   10746: 
                   10747: sub dirlist {
1.955     raeburn  10748:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10749:     $uri=~s/^\///;
                   10750:     $uri=~s/\/$//;
1.253     stredwic 10751:     my ($udom, $uname);
1.955     raeburn  10752:     if ($getuserdir) {
1.253     stredwic 10753:         $udom = $userdomain;
                   10754:         $uname = $username;
1.955     raeburn  10755:     } else {
                   10756:         (undef,$udom,$uname)=split(/\//,$uri);
                   10757:         if(defined($userdomain)) {
                   10758:             $udom = $userdomain;
                   10759:         }
                   10760:         if(defined($username)) {
                   10761:             $uname = $username;
                   10762:         }
1.253     stredwic 10763:     }
1.955     raeburn  10764:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10765: 
1.955     raeburn  10766:     $dirRoot = $perlvar{'lonDocRoot'};
                   10767:     if (defined($getpropath)) {
                   10768:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10769:         $dirRoot =~ s/\/$//;
1.955     raeburn  10770:     } elsif (defined($getuserdir)) {
                   10771:         my $subdir=$uname.'__';
                   10772:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10773:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10774:                    ."/$udom/$subdir/$uname";
                   10775:     } elsif (defined($alternateRoot)) {
                   10776:         $dirRoot = $alternateRoot;
1.751     banghart 10777:     }
1.253     stredwic 10778: 
                   10779:     if($udom) {
                   10780:         if($uname) {
1.1135    raeburn  10781:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10782:             if ($uhome eq 'no_host') {
                   10783:                 return ([],'no_host');
                   10784:             }
1.955     raeburn  10785:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10786:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10787:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10788:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10789:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10790:             } else {
                   10791:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10792:             }
1.605     matthew  10793:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10794:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10795:                 @listing_results = split(/:/,$listing);
                   10796:             } else {
                   10797:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10798:             }
1.1135    raeburn  10799:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10800:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10801:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10802:                 return ([],$listing);
                   10803:             } else {
                   10804:                 return (\@listing_results);
1.1135    raeburn  10805:             }
1.955     raeburn  10806:         } elsif(!$alternateRoot) {
1.1136    raeburn  10807:             my (%allusers,%listerror);
1.841     albertel 10808: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10809:  	    foreach my $tryserver (keys(%servers)) {
                   10810:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10811:                                   &escape($udom),$tryserver);
                   10812:                 if ($listing eq 'unknown_cmd') {
                   10813: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10814: 				      $udom, $tryserver);
                   10815:                 } else {
                   10816:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10817:                 }
1.841     albertel 10818: 		if ($listing eq 'unknown_cmd') {
                   10819: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10820: 				      $udom, $tryserver);
                   10821: 		    @listing_results = split(/:/,$listing);
                   10822: 		} else {
                   10823: 		    @listing_results =
                   10824: 			map { &unescape($_); } split(/:/,$listing);
                   10825: 		}
1.1136    raeburn  10826:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10827:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10828:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10829:                     $listerror{$tryserver} = $listing;
                   10830:                 } else {
1.841     albertel 10831: 		    foreach my $line (@listing_results) {
                   10832: 			my ($entry) = split(/&/,$line,2);
                   10833: 			$allusers{$entry} = 1;
                   10834: 		    }
                   10835: 		}
1.253     stredwic 10836:             }
1.1136    raeburn  10837:             my @alluserslist=();
1.800     albertel 10838:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10839:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10840:             }
1.1172.2.80  raeburn  10841:             if (!%listerror) {
                   10842:                 # no errors
                   10843:                 return (\@alluserslist);
                   10844:             } elsif (scalar(keys(%servers)) == 1) {
                   10845:                 # one library server, one error
                   10846:                 my ($key) = keys(%listerror);
                   10847:                 return (\@alluserslist, $listerror{$key});
                   10848:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10849:                 # con_lost indicates that we might miss data from at least one
                   10850:                 # library server
                   10851:                 return (\@alluserslist, 'con_lost');
                   10852:             } else {
                   10853:                 # multiple library servers and no con_lost -> data should be
                   10854:                 # complete.
                   10855:                 return (\@alluserslist);
                   10856:             }
                   10857: 
1.253     stredwic 10858:         } else {
1.1136    raeburn  10859:             return ([],'missing username');
1.253     stredwic 10860:         }
1.955     raeburn  10861:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10862:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10863:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10864:         return (\@all_domains);
1.955     raeburn  10865:     } else {
1.1136    raeburn  10866:         return ([],'missing domain');
1.275     stredwic 10867:     }
                   10868: }
                   10869: 
                   10870: # --------------------------------------------- GetFileTimestamp
                   10871: # This function utilizes dirlist and returns the date stamp for
                   10872: # when it was last modified.  It will also return an error of -1
                   10873: # if an error occurs
                   10874: 
                   10875: sub GetFileTimestamp {
1.955     raeburn  10876:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10877:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10878:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10879:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10880:                                     undef,$getuserdir);
                   10881:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10882:         return -1;
                   10883:     }
                   10884:     if (ref($fileref) eq 'ARRAY') {
                   10885:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10886:         # @stats contains first the filename, then the stat output
                   10887:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10888:     } else {
                   10889:         return -1;
1.253     stredwic 10890:     }
1.26      www      10891: }
                   10892: 
1.712     albertel 10893: sub stat_file {
                   10894:     my ($uri) = @_;
1.787     albertel 10895:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10896: 
1.955     raeburn  10897:     my ($udom,$uname,$file);
1.712     albertel 10898:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10899: 	($udom,$uname,$file) =
1.811     albertel 10900: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10901: 	$file = 'userfiles/'.$file;
                   10902:     }
                   10903:     if ($uri =~ m-^/res/-) {
                   10904: 	($udom,$uname) = 
1.807     albertel 10905: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10906: 	$file = $uri;
                   10907:     }
                   10908: 
                   10909:     if (!$udom || !$uname || !$file) {
                   10910: 	# unable to handle the uri
                   10911: 	return ();
                   10912:     }
1.956     raeburn  10913:     my $getpropath;
                   10914:     if ($file =~ /^userfiles\//) {
                   10915:         $getpropath = 1;
                   10916:     }
1.1136    raeburn  10917:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10918:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10919:         return ();
                   10920:     } else {
                   10921:         if (ref($listref) eq 'ARRAY') {
                   10922:             my @stats = split('&',$listref->[0]);
                   10923: 	    shift(@stats); #filename is first
                   10924: 	    return @stats;
                   10925:         }
1.712     albertel 10926:     }
                   10927:     return ();
                   10928: }
                   10929: 
1.26      www      10930: # -------------------------------------------------------- Value of a Condition
                   10931: 
1.713     albertel 10932: # gets the value of a specific preevaluated condition
                   10933: #    stored in the string  $env{user.state.<cid>}
                   10934: # or looks up a condition reference in the bighash and if if hasn't
                   10935: # already been evaluated recurses into docondval to get the value of
                   10936: # the condition, then memoizing it to 
                   10937: #   $env{user.state.<cid>.<condition>}
1.40      www      10938: sub directcondval {
                   10939:     my $number=shift;
1.620     albertel 10940:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10941: 	&Apache::lonuserstate::evalstate();
                   10942:     }
1.713     albertel 10943:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10944: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10945:     } elsif ($number =~ /^_/) {
                   10946: 	my $sub_condition;
                   10947: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10948: 		&GDBM_READER(),0640)) {
                   10949: 	    $sub_condition=$bighash{'conditions'.$number};
                   10950: 	    untie(%bighash);
                   10951: 	}
                   10952: 	my $value = &docondval($sub_condition);
1.949     raeburn  10953: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10954: 	return $value;
                   10955:     }
1.620     albertel 10956:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10957:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10958:     } else {
                   10959:        return 2;
                   10960:     }
                   10961: }
                   10962: 
1.713     albertel 10963: # get the collection of conditions for this resource
1.26      www      10964: sub condval {
                   10965:     my $condidx=shift;
1.54      www      10966:     my $allpathcond='';
1.713     albertel 10967:     foreach my $cond (split(/\|/,$condidx)) {
                   10968: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10969: 	    $allpathcond.=
                   10970: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10971: 	}
1.191     harris41 10972:     }
1.54      www      10973:     $allpathcond=~s/\|$//;
1.713     albertel 10974:     return &docondval($allpathcond);
                   10975: }
                   10976: 
                   10977: #evaluates an expression of conditions
                   10978: sub docondval {
                   10979:     my ($allpathcond) = @_;
                   10980:     my $result=0;
                   10981:     if ($env{'request.course.id'}
                   10982: 	&& defined($allpathcond)) {
                   10983: 	my $operand='|';
                   10984: 	my @stack;
                   10985: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10986: 	    if ($chunk eq '(') {
                   10987: 		push @stack,($operand,$result);
                   10988: 	    } elsif ($chunk eq ')') {
                   10989: 		my $before=pop @stack;
                   10990: 		if (pop @stack eq '&') {
                   10991: 		    $result=$result>$before?$before:$result;
                   10992: 		} else {
                   10993: 		    $result=$result>$before?$result:$before;
                   10994: 		}
                   10995: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10996: 		$operand=$chunk;
                   10997: 	    } else {
                   10998: 		my $new=directcondval($chunk);
                   10999: 		if ($operand eq '&') {
                   11000: 		    $result=$result>$new?$new:$result;
                   11001: 		} else {
                   11002: 		    $result=$result>$new?$result:$new;
                   11003: 		}
                   11004: 	    }
                   11005: 	}
1.26      www      11006:     }
                   11007:     return $result;
1.421     albertel 11008: }
                   11009: 
                   11010: # ---------------------------------------------------- Devalidate courseresdata
                   11011: 
                   11012: sub devalidatecourseresdata {
                   11013:     my ($coursenum,$coursedomain)=@_;
                   11014:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11015:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11016: }
                   11017: 
1.763     www      11018: 
1.200     www      11019: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11020: #
                   11021: #  Parameters:
                   11022: #      $coursenum    - Number of the course.
                   11023: #      $coursedomain - Domain at which the course was created.
                   11024: #  Returns:
                   11025: #     A hash of the course parameters along (I think) with timestamps
                   11026: #     and version info.
1.877     foxr     11027: 
1.624     albertel 11028: sub get_courseresdata {
                   11029:     my ($coursenum,$coursedomain)=@_;
1.200     www      11030:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11031:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11032:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11033:     my %dumpreply;
1.417     albertel 11034:     unless (defined($cached)) {
1.624     albertel 11035: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11036: 	$result=\%dumpreply;
1.251     albertel 11037: 	my ($tmp) = keys(%dumpreply);
                   11038: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11039: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11040: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11041: 	    return $tmp;
1.416     albertel 11042: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11043: 	    $result=undef;
1.599     albertel 11044: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11045: 	}
                   11046:     }
1.624     albertel 11047:     return $result;
                   11048: }
                   11049: 
1.633     albertel 11050: sub devalidateuserresdata {
                   11051:     my ($uname,$udom)=@_;
                   11052:     my $hashid="$udom:$uname";
                   11053:     &devalidate_cache_new('userres',$hashid);
                   11054: }
                   11055: 
1.624     albertel 11056: sub get_userresdata {
                   11057:     my ($uname,$udom)=@_;
                   11058:     #most student don\'t have any data set, check if there is some data
                   11059:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11060: 
                   11061:     my $hashid="$udom:$uname";
                   11062:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11063:     if (!defined($cached)) {
                   11064: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11065: 	$result=\%resourcedata;
                   11066: 	&do_cache_new('userres',$hashid,$result,600);
                   11067:     }
                   11068:     my ($tmp)=keys(%$result);
                   11069:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11070: 	return $result;
                   11071:     }
                   11072:     #error 2 occurs when the .db doesn't exist
                   11073:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11074:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11075: 	    &logthis("<font color=\"blue\">WARNING:".
                   11076: 		     " Trying to get resource data for ".
                   11077: 		     $uname." at ".$udom.": ".
                   11078: 		     $tmp."</font>");
                   11079:         }
1.624     albertel 11080:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11081: 	#&EXT_cache_set($udom,$uname);
                   11082: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11083: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11084:     }
                   11085:     return $tmp;
                   11086: }
1.879     foxr     11087: #----------------------------------------------- resdata - return resource data
                   11088: #  Purpose:
                   11089: #    Return resource data for either users or for a course.
                   11090: #  Parameters:
                   11091: #     $name      - Course/user name.
                   11092: #     $domain    - Name of the domain the user/course is registered on.
                   11093: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11094: #     @which     - Array of names of resources desired.
                   11095: #  Returns:
                   11096: #     The value of the first reasource in @which that is found in the
                   11097: #     resource hash.
                   11098: #  Exceptional Conditions:
                   11099: #     If the $type passed in is not valid (not the string 'course' or 
                   11100: #     'user', an undefined  reference is returned.
                   11101: #     If none of the resources are found, an undef is returned
1.624     albertel 11102: sub resdata {
                   11103:     my ($name,$domain,$type,@which)=@_;
                   11104:     my $result;
                   11105:     if ($type eq 'course') {
                   11106: 	$result=&get_courseresdata($name,$domain);
                   11107:     } elsif ($type eq 'user') {
                   11108: 	$result=&get_userresdata($name,$domain);
                   11109:     }
                   11110:     if (!ref($result)) { return $result; }    
1.251     albertel 11111:     foreach my $item (@which) {
1.927     albertel 11112: 	if (defined($result->{$item->[0]})) {
                   11113: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11114: 	}
1.250     albertel 11115:     }
1.291     albertel 11116:     return undef;
1.200     www      11117: }
                   11118: 
1.1172.2.31  raeburn  11119: sub get_numsuppfiles {
                   11120:     my ($cnum,$cdom,$ignorecache)=@_;
                   11121:     my $hashid=$cnum.':'.$cdom;
                   11122:     my ($suppcount,$cached);
                   11123:     unless ($ignorecache) {
                   11124:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11125:     }
                   11126:     unless (defined($cached)) {
                   11127:         my $chome=&homeserver($cnum,$cdom);
                   11128:         unless ($chome eq 'no_host') {
                   11129:             ($suppcount,my $errors) = (0,0);
                   11130:             my $suppmap = 'supplemental.sequence';
                   11131:             ($suppcount,$errors) =
                   11132:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11133:         }
                   11134:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11135:     }
                   11136:     return $suppcount;
                   11137: }
                   11138: 
1.379     matthew  11139: #
                   11140: # EXT resource caching routines
                   11141: #
                   11142: 
                   11143: sub clear_EXT_cache_status {
1.383     albertel 11144:     &delenv('cache.EXT.');
1.379     matthew  11145: }
                   11146: 
                   11147: sub EXT_cache_status {
                   11148:     my ($target_domain,$target_user) = @_;
1.383     albertel 11149:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11150:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11151:         # We know already the user has no data
                   11152:         return 1;
                   11153:     } else {
                   11154:         return 0;
                   11155:     }
                   11156: }
                   11157: 
                   11158: sub EXT_cache_set {
                   11159:     my ($target_domain,$target_user) = @_;
1.383     albertel 11160:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11161:     #&appenv({$cachename => time});
1.379     matthew  11162: }
                   11163: 
1.28      www      11164: # --------------------------------------------------------- Value of a Variable
1.58      www      11165: sub EXT {
1.715     albertel 11166: 
1.1172.2.28  raeburn  11167:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11168:     unless ($varname) { return ''; }
1.218     albertel 11169:     #get real user name/domain, courseid and symb
                   11170:     my $courseid;
1.359     albertel 11171:     my $publicuser;
1.427     www      11172:     if ($symbparm) {
                   11173: 	$symbparm=&get_symb_from_alias($symbparm);
                   11174:     }
1.218     albertel 11175:     if (!($uname && $udom)) {
1.790     albertel 11176:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11177:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11178:     } else {
1.620     albertel 11179: 	$courseid=$env{'request.course.id'};
1.218     albertel 11180:     }
1.48      www      11181:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11182:     my $rest;
1.320     albertel 11183:     if (defined($therest[0])) {
1.48      www      11184:        $rest=join('.',@therest);
                   11185:     } else {
                   11186:        $rest='';
                   11187:     }
1.320     albertel 11188: 
1.57      www      11189:     my $qualifierrest=$qualifier;
                   11190:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11191:     my $spacequalifierrest=$space;
                   11192:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11193:     if ($realm eq 'user') {
1.48      www      11194: # --------------------------------------------------------------- user.resource
                   11195: 	if ($space eq 'resource') {
1.651     albertel 11196: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11197: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11198: 		 &&
1.744     albertel 11199: 		 ($symbparm eq &symbread()) ) {	
                   11200: 		# if we are in the middle of processing the resource the
                   11201: 		# get the value we are planning on committing
                   11202:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11203:                     return $Apache::lonhomework::results{$qualifierrest};
                   11204:                 } else {
                   11205:                     return $Apache::lonhomework::history{$qualifierrest};
                   11206:                 }
1.335     albertel 11207: 	    } else {
1.359     albertel 11208: 		my %restored;
1.620     albertel 11209: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11210: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11211: 		} else {
                   11212: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11213: 		}
1.335     albertel 11214: 		return $restored{$qualifierrest};
                   11215: 	    }
1.48      www      11216: # ----------------------------------------------------------------- user.access
                   11217:         } elsif ($space eq 'access') {
1.218     albertel 11218: 	    # FIXME - not supporting calls for a specific user
1.48      www      11219:             return &allowed($qualifier,$rest);
                   11220: # ------------------------------------------ user.preferences, user.environment
                   11221:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11222: 	    if (($uname eq $env{'user.name'}) &&
                   11223: 		($udom eq $env{'user.domain'})) {
                   11224: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11225: 	    } else {
1.359     albertel 11226: 		my %returnhash;
                   11227: 		if (!$publicuser) {
                   11228: 		    %returnhash=&userenvironment($udom,$uname,
                   11229: 						 $qualifierrest);
                   11230: 		}
1.218     albertel 11231: 		return $returnhash{$qualifierrest};
                   11232: 	    }
1.48      www      11233: # ----------------------------------------------------------------- user.course
                   11234:         } elsif ($space eq 'course') {
1.218     albertel 11235: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11236:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11237: # ------------------------------------------------------------------- user.role
                   11238:         } elsif ($space eq 'role') {
1.218     albertel 11239: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11240:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11241:             if ($qualifier eq 'value') {
                   11242: 		return $role;
                   11243:             } elsif ($qualifier eq 'extent') {
                   11244:                 return $where;
                   11245:             }
                   11246: # ----------------------------------------------------------------- user.domain
                   11247:         } elsif ($space eq 'domain') {
1.218     albertel 11248:             return $udom;
1.48      www      11249: # ------------------------------------------------------------------- user.name
                   11250:         } elsif ($space eq 'name') {
1.218     albertel 11251:             return $uname;
1.48      www      11252: # ---------------------------------------------------- Any other user namespace
1.29      www      11253:         } else {
1.359     albertel 11254: 	    my %reply;
                   11255: 	    if (!$publicuser) {
                   11256: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11257: 	    }
                   11258: 	    return $reply{$qualifierrest};
1.48      www      11259:         }
1.236     www      11260:     } elsif ($realm eq 'query') {
                   11261: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11262:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11263: 						[$spacequalifierrest]);
1.620     albertel 11264: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11265:    } elsif ($realm eq 'request') {
1.48      www      11266: # ------------------------------------------------------------- request.browser
                   11267:         if ($space eq 'browser') {
1.1145    bisitz   11268:             return $env{'browser.'.$qualifier};
1.57      www      11269: # ------------------------------------------------------------ request.filename
                   11270:         } else {
1.620     albertel 11271:             return $env{'request.'.$spacequalifierrest};
1.29      www      11272:         }
1.28      www      11273:     } elsif ($realm eq 'course') {
1.48      www      11274: # ---------------------------------------------------------- course.description
1.620     albertel 11275:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11276:     } elsif ($realm eq 'resource') {
1.165     www      11277: 
1.620     albertel 11278: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11279: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11280: 	}
1.693     albertel 11281: 
1.1172.2.30  raeburn  11282:         if ($qualifier eq '') {
                   11283: 	    if ($space eq 'title') {
                   11284: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11285: 	        return &gettitle($symbparm);
                   11286: 	    }
1.693     albertel 11287: 	
1.1172.2.30  raeburn  11288: 	    if ($space eq 'map') {
                   11289: 	        my ($map) = &decode_symb($symbparm);
                   11290: 	        return &symbread($map);
                   11291: 	    }
                   11292:             if ($space eq 'maptitle') {
                   11293:                 my ($map) = &decode_symb($symbparm);
                   11294:                 return &gettitle($map);
                   11295:             }
                   11296: 	    if ($space eq 'filename') {
                   11297: 	        if ($symbparm) {
                   11298: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11299: 	        }
                   11300: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11301: 	    }
1.1172.2.30  raeburn  11302: 
                   11303:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11304:                 if ($space eq 'visibleparts') {
                   11305:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11306:                     my $item;
                   11307:                     if (ref($navmap)) {
                   11308:                         my $res = $navmap->getBySymb($symbparm);
                   11309:                         my $parts = $res->parts();
                   11310:                         if (ref($parts) eq 'ARRAY') {
                   11311:                             $item = join(',',@{$parts});
                   11312:                         }
                   11313:                         undef($navmap);
                   11314:                     }
                   11315:                     return $item;
                   11316:                 }
                   11317:             }
                   11318:         }
1.693     albertel 11319: 
                   11320: 	my ($section, $group, @groups);
1.593     albertel 11321: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11322:         if (($courseid eq '') && ($cid)) {
                   11323:             $courseid = $cid;
                   11324:         }
                   11325: 	if (($symbparm && $courseid) && 
                   11326: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11327: 
1.218     albertel 11328: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11329: 
1.60      www      11330: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11331: 	    my $symbp=$symbparm;
1.735     albertel 11332: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11333: 
                   11334: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11335: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11336: 
1.620     albertel 11337: 	    if (($env{'user.name'} eq $uname) &&
                   11338: 		($env{'user.domain'} eq $udom)) {
                   11339: 		$section=$env{'request.course.sec'};
1.733     raeburn  11340:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11341:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11342: 	    } else {
1.539     albertel 11343: 		if (! defined($usection)) {
1.551     albertel 11344: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11345: 		} else {
                   11346: 		    $section = $usection;
                   11347: 		}
1.733     raeburn  11348:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11349: 	    }
                   11350: 
                   11351: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11352: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11353: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11354: 
1.593     albertel 11355: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11356: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11357: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11358: 
1.60      www      11359: # ----------------------------------------------------------- first, check user
1.624     albertel 11360: 
                   11361: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11362: 				       ([$courselevelr,'resource'],
                   11363: 					[$courselevelm,'map'     ],
                   11364: 					[$courselevel, 'course'  ]));
1.931     albertel 11365: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11366: 
1.594     albertel 11367: # ------------------------------------------------ second, check some of course
1.684     raeburn  11368:             my $coursereply;
1.691     raeburn  11369:             if (@groups > 0) {
                   11370:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11371:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11372:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11373:             }
1.96      www      11374: 
1.684     raeburn  11375: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11376: 				  $env{'course.'.$courseid.'.domain'},
                   11377: 				  'course',
                   11378: 				  ([$seclevelr,   'resource'],
                   11379: 				   [$seclevelm,   'map'     ],
                   11380: 				   [$seclevel,    'course'  ],
                   11381: 				   [$courselevelr,'resource']));
                   11382: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11383: 
1.60      www      11384: # ------------------------------------------------------ third, check map parms
1.218     albertel 11385: 	    my %parmhash=();
                   11386: 	    my $thisparm='';
                   11387: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11388: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11389: 		    &GDBM_READER(),0640)) {
1.218     albertel 11390: 		$thisparm=$parmhash{$symbparm};
                   11391: 		untie(%parmhash);
                   11392: 	    }
1.927     albertel 11393: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11394: 	}
1.594     albertel 11395: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11396: 
1.218     albertel 11397: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11398: 	my $filename;
                   11399: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11400: 	if ($symbparm) {
1.409     www      11401: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11402: 	} else {
1.620     albertel 11403: 	    $filename=$env{'request.filename'};
1.282     albertel 11404: 	}
                   11405: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11406: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11407: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11408: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11409: 
1.927     albertel 11410: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11411: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11412: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11413: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11414: 				     $env{'course.'.$courseid.'.domain'},
                   11415: 				     'course',
1.927     albertel 11416: 				     ([$courselevelm,'map'   ],
                   11417: 				      [$courselevel, 'course']));
                   11418: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11419: 	}
1.145     www      11420: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11421: 	unless ($space eq '0') {
1.336     albertel 11422: 	    my @parts=split(/_/,$space);
                   11423: 	    my $id=pop(@parts);
                   11424: 	    my $part=join('_',@parts);
                   11425: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11426: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11427: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11428: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11429: 	}
1.395     albertel 11430: 	if ($recurse) { return undef; }
                   11431: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11432: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11433: # ---------------------------------------------------- Any other user namespace
                   11434:     } elsif ($realm eq 'environment') {
                   11435: # ----------------------------------------------------------------- environment
1.620     albertel 11436: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11437: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11438: 	} else {
1.770     albertel 11439: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11440: 		return '';
                   11441: 	    }
1.219     albertel 11442: 	    my %returnhash=&userenvironment($udom,$uname,
                   11443: 					    $spacequalifierrest);
                   11444: 	    return $returnhash{$spacequalifierrest};
                   11445: 	}
1.28      www      11446:     } elsif ($realm eq 'system') {
1.48      www      11447: # ----------------------------------------------------------------- system.time
                   11448: 	if ($space eq 'time') {
                   11449: 	    return time;
                   11450:         }
1.696     albertel 11451:     } elsif ($realm eq 'server') {
                   11452: # ----------------------------------------------------------------- system.time
                   11453: 	if ($space eq 'name') {
                   11454: 	    return $ENV{'SERVER_NAME'};
                   11455:         }
1.28      www      11456:     }
1.48      www      11457:     return '';
1.61      www      11458: }
                   11459: 
1.927     albertel 11460: sub get_reply {
                   11461:     my ($reply_value) = @_;
1.940     raeburn  11462:     if (ref($reply_value) eq 'ARRAY') {
                   11463:         if (wantarray) {
                   11464: 	    return @$reply_value;
                   11465:         }
                   11466:         return $reply_value->[0];
                   11467:     } else {
                   11468:         return $reply_value;
1.927     albertel 11469:     }
                   11470: }
                   11471: 
1.691     raeburn  11472: sub check_group_parms {
                   11473:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11474:     my @groupitems = ();
                   11475:     my $resultitem;
1.927     albertel 11476:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11477:     foreach my $group (@{$groups}) {
                   11478:         foreach my $level (@levels) {
1.927     albertel 11479:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11480:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11481:         }
                   11482:     }
                   11483:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11484:                             $env{'course.'.$courseid.'.domain'},
                   11485:                                      'course',@groupitems);
                   11486:     return $coursereply;
                   11487: }
                   11488: 
                   11489: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11490:     my ($courseid,@groups) = @_;
                   11491:     @groups = sort(@groups);
1.691     raeburn  11492:     return @groups;
                   11493: }
                   11494: 
1.395     albertel 11495: sub packages_tab_default {
                   11496:     my ($uri,$varname)=@_;
                   11497:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11498: 
                   11499:     my (@extension,@specifics,$do_default);
                   11500:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11501: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11502: 	if ($pack_type eq 'default') {
                   11503: 	    $do_default=1;
                   11504: 	} elsif ($pack_type eq 'extension') {
                   11505: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11506: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11507: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11508: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11509: 	}
                   11510:     }
                   11511:     # first look for a package that matches the requested part id
                   11512:     foreach my $package (@specifics) {
                   11513: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11514: 	next if ($pack_part ne $part);
                   11515: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11516: 	    return $packagetab{"$pack_type&$name&default"};
                   11517: 	}
                   11518:     }
                   11519:     # look for any possible matching non extension_ package
                   11520:     foreach my $package (@specifics) {
                   11521: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11522: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11523: 	    return $packagetab{"$pack_type&$name&default"};
                   11524: 	}
1.585     albertel 11525: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11526: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11527: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11528: 	}
                   11529:     }
1.738     albertel 11530:     # look for any posible extension_ match
                   11531:     foreach my $package (@extension) {
                   11532: 	my ($package,$pack_type)=@{$package};
                   11533: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11534: 	    return $packagetab{"$pack_type&$name&default"};
                   11535: 	}
                   11536: 	if (defined($packagetab{$package."&$name&default"})) {
                   11537: 	    return $packagetab{$package."&$name&default"};
                   11538: 	}
                   11539:     }
                   11540:     # look for a global default setting
                   11541:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11542: 	return $packagetab{"default&$name&default"};
                   11543:     }
1.395     albertel 11544:     return undef;
                   11545: }
                   11546: 
1.334     albertel 11547: sub add_prefix_and_part {
                   11548:     my ($prefix,$part)=@_;
                   11549:     my $keyroot;
                   11550:     if (defined($prefix) && $prefix !~ /^__/) {
                   11551: 	# prefix that has a part already
                   11552: 	$keyroot=$prefix;
                   11553:     } elsif (defined($prefix)) {
                   11554: 	# prefix that is missing a part
                   11555: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11556:     } else {
                   11557: 	# no prefix at all
                   11558: 	if (defined($part)) { $keyroot='_'.$part; }
                   11559:     }
                   11560:     return $keyroot;
                   11561: }
                   11562: 
1.71      www      11563: # ---------------------------------------------------------------- Get metadata
                   11564: 
1.599     albertel 11565: my %metaentry;
1.1070    www      11566: my %importedpartids;
1.1172.2.99  raeburn  11567: my %importedrespids;
1.71      www      11568: sub metadata {
1.176     www      11569:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11570:     $uri=&declutter($uri);
1.288     albertel 11571:     # if it is a non metadata possible uri return quickly
1.529     albertel 11572:     if (($uri eq '') || 
                   11573: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11574: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11575:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11576: 	return undef;
                   11577:     }
1.1172.2.49  raeburn  11578:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11579: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11580: 	return undef;
1.288     albertel 11581:     }
1.73      www      11582:     my $filename=$uri;
                   11583:     $uri=~s/\.meta$//;
1.172     www      11584: #
                   11585: # Is the metadata already cached?
1.177     www      11586: # Look at timestamp of caching
1.172     www      11587: # Everything is cached by the main uri, libraries are never directly cached
                   11588: #
1.428     albertel 11589:     if (!defined($liburi)) {
1.599     albertel 11590: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11591: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11592:     }
                   11593:     {
1.1069    www      11594: # Imported parts would go here
1.1172.2.99  raeburn  11595:         my @origfiletagids=();
1.1069    www      11596:         my $importedparts=0;
1.1172.2.99  raeburn  11597: 
                   11598: # Imported responseids would go here
                   11599:         my $importedresponses=0;
1.172     www      11600: #
                   11601: # Is this a recursive call for a library?
                   11602: #
1.599     albertel 11603: #	if (! exists($metacache{$uri})) {
                   11604: #	    $metacache{$uri}={};
                   11605: #	}
1.924     albertel 11606: 	my $cachetime = 60*60;
1.171     www      11607:         if ($liburi) {
                   11608: 	    $liburi=&declutter($liburi);
                   11609:             $filename=$liburi;
1.401     bowersj2 11610:         } else {
1.599     albertel 11611: 	    &devalidate_cache_new('meta',$uri);
                   11612: 	    undef(%metaentry);
1.401     bowersj2 11613: 	}
1.140     www      11614:         my %metathesekeys=();
1.73      www      11615:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11616: 	my $metastring;
1.1140    www      11617: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11618: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11619: 	    $metastring = 
1.929     albertel 11620: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11621: 					  ('grade_target' => 'meta'));
                   11622: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11623: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11624:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11625: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11626: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11627: 	    $metastring=&getfile($file);
1.489     albertel 11628: 	}
1.208     albertel 11629:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11630:         my $token;
1.140     www      11631:         undef %metathesekeys;
1.71      www      11632:         while ($token=$parser->get_token) {
1.339     albertel 11633: 	    if ($token->[0] eq 'S') {
                   11634: 		if (defined($token->[2]->{'package'})) {
1.172     www      11635: #
                   11636: # This is a package - get package info
                   11637: #
1.339     albertel 11638: 		    my $package=$token->[2]->{'package'};
                   11639: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11640: 		    if (defined($token->[2]->{'id'})) { 
                   11641: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11642: 		    }
1.599     albertel 11643: 		    if ($metaentry{':packages'}) {
                   11644: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11645: 		    } else {
1.599     albertel 11646: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11647: 		    }
1.736     albertel 11648: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11649: 			my $part=$keyroot;
                   11650: 			$part=~s/^\_//;
1.736     albertel 11651: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11652: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11653: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11654: 			    # ignore package.tab specified default values
                   11655:                             # here &package_tab_default() will fetch those
                   11656: 			    if ($subp eq 'default') { next; }
1.736     albertel 11657: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11658: 			    my $unikey;
                   11659: 			    if ($pack =~ /_0$/) {
                   11660: 				$unikey='parameter_0_'.$name;
                   11661: 				$part=0;
                   11662: 			    } else {
                   11663: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11664: 			    }
1.339     albertel 11665: 			    if ($subp eq 'display') {
                   11666: 				$value.=' [Part: '.$part.']';
                   11667: 			    }
1.599     albertel 11668: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11669: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11670: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11671: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11672: 			    }
1.599     albertel 11673: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11674: 				$metaentry{':'.$unikey}=
                   11675: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11676: 			    }
1.339     albertel 11677: 			}
                   11678: 		    }
                   11679: 		} else {
1.172     www      11680: #
                   11681: # This is not a package - some other kind of start tag
1.339     albertel 11682: #
                   11683: 		    my $entry=$token->[1];
1.1068    www      11684: 		    my $unikey='';
1.175     www      11685: 
1.339     albertel 11686: 		    if ($entry eq 'import') {
1.175     www      11687: #
                   11688: # Importing a library here
1.339     albertel 11689: #
1.1067    www      11690:                         my $location=$parser->get_text('/import');
                   11691:                         my $dir=$filename;
                   11692:                         $dir=~s|[^/]*$||;
                   11693:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11694: 
                   11695:                         my $importid=$token->[2]->{'id'};
1.1068    www      11696:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11697: #
                   11698: # Check metadata for imported file to
                   11699: # see if it contained response items
                   11700: #
                   11701:                         my %currmetaentry = %metaentry;
                   11702:                         my $libresponseorder = &metadata($location,'responseorder');
                   11703:                         my $origfile;
                   11704:                         if ($libresponseorder ne '') {
                   11705:                             if ($#origfiletagids<0) {
                   11706:                                 undef(%importedrespids);
                   11707:                                 undef(%importedpartids);
                   11708:                             }
                   11709:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11710:                             if (@{$importedrespids{$importid}} > 0) {
                   11711:                                 $importedresponses = 1;
                   11712: # We need to get the original file and the imported file to get the response order correct
                   11713: # Load and inspect original file
                   11714:                                 if ($#origfiletagids<0) {
                   11715:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11716:                                     $origfile=&getfile($origfilelocation);
                   11717:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11718:                                 }
                   11719:                             }
                   11720:                         }
                   11721: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11722: # hash populated for imported library file
                   11723:                         %metaentry = %currmetaentry;
                   11724:                         undef(%currmetaentry);
1.1068    www      11725:                         if ($importmode eq 'problem') {
1.1069    www      11726: # Import as problem/response
1.1068    www      11727:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11728:                         } elsif ($importmode eq 'part') {
                   11729: # Import as part(s)
1.1069    www      11730:                            $importedparts=1;
                   11731: # We need to get the original file and the imported file to get the part order correct
                   11732: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11733: # Load and inspect original file if we didn't do that already
                   11734:                            if ($#origfiletagids<0) {
                   11735:                                undef(%importedrespids);
                   11736:                                undef(%importedpartids);
                   11737:                                if ($origfile eq '') {
                   11738:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11739:                                    $origfile=&getfile($origfilelocation);
                   11740:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11741:                                }
1.1070    www      11742:                            }
                   11743: 
1.1069    www      11744: # Load and inspect imported file
                   11745:                            my $impfile=&getfile($location);
                   11746:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11747:                            if ($#impfilepartids>=0) {
                   11748: # This problem had parts
1.1070    www      11749:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11750:                            } else {
                   11751: # Importing by turning a single problem into a problem part
                   11752: # It gets the import-tags ID as part-ID
                   11753:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11754:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11755:                            }
1.1068    www      11756:                         } else {
                   11757: # Normal import
                   11758:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11759:                            if (defined($token->[2]->{'id'})) {
                   11760:                               $unikey.='_'.$token->[2]->{'id'};
                   11761:                            }
1.1067    www      11762:                         }
                   11763: 
1.339     albertel 11764: 			if ($depthcount<20) {
1.736     albertel 11765: 			    my $metadata = 
                   11766: 				&metadata($uri,'keys', $location,$unikey,
                   11767: 					  $depthcount+1);
                   11768: 			    foreach my $meta (split(',',$metadata)) {
                   11769: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11770: 				$metathesekeys{$meta}=1;
1.339     albertel 11771: 			    }
1.1068    www      11772: 			
                   11773:                         }
1.1067    www      11774: 		    } else {
                   11775: #
                   11776: # Not importing, some other kind of non-package, non-library start tag
                   11777: # 
                   11778:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11779:                         if (defined($token->[2]->{'id'})) {
                   11780:                             $unikey.='_'.$token->[2]->{'id'};
                   11781:                         }
1.339     albertel 11782: 			if (defined($token->[2]->{'name'})) { 
                   11783: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11784: 			}
                   11785: 			$metathesekeys{$unikey}=1;
1.736     albertel 11786: 			foreach my $param (@{$token->[3]}) {
                   11787: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11788: 				$token->[2]->{$param};
1.339     albertel 11789: 			}
                   11790: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11791: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11792: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11793: 		 # only ws inside the tag, and not in default, so use default
                   11794: 		 # as value
1.599     albertel 11795: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11796: 			} elsif ( $internaltext =~ /\S/ ) {
                   11797: 		  # something interesting inside the tag
                   11798: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11799: 			} else {
1.908     albertel 11800: 		  # no interesting values, don't set a default
1.339     albertel 11801: 			}
1.172     www      11802: # end of not-a-package not-a-library import
1.339     albertel 11803: 		    }
1.172     www      11804: # end of not-a-package start tag
1.339     albertel 11805: 		}
1.172     www      11806: # the next is the end of "start tag"
1.339     albertel 11807: 	    }
                   11808: 	}
1.483     albertel 11809: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11810: 	$extension = lc($extension);
                   11811: 	if ($extension eq 'htm') { $extension='html'; }
                   11812: 
1.737     albertel 11813: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11814: 	    #no specific packages #how's our extension
                   11815: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11816: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11817: 					 \%metathesekeys);
                   11818: 	}
1.883     albertel 11819: 
                   11820: 	if (!exists($metaentry{':packages'})
                   11821: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11822: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11823: 		#no specific packages well let's get default then
                   11824: 		if ($key!~/^default&/) { next; }
1.488     albertel 11825: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11826: 					     \%metathesekeys);
                   11827: 	    }
                   11828: 	}
1.338     www      11829: # are there custom rights to evaluate
1.599     albertel 11830: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11831: 
1.338     www      11832:     #
                   11833:     # Importing a rights file here
1.339     albertel 11834:     #
                   11835: 	    unless ($depthcount) {
1.599     albertel 11836: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11837: 		my $dir=$filename;
                   11838: 		$dir=~s|[^/]*$||;
                   11839: 		$location=&filelocation($dir,$location);
1.736     albertel 11840: 		my $rights_metadata =
                   11841: 		    &metadata($uri,'keys',$location,'_rights',
                   11842: 			      $depthcount+1);
                   11843: 		foreach my $rights (split(',',$rights_metadata)) {
                   11844: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11845: 		    $metathesekeys{$rights}=1;
1.339     albertel 11846: 		}
                   11847: 	    }
                   11848: 	}
1.737     albertel 11849: 	# uniqifiy package listing
                   11850: 	my %seen;
                   11851: 	my @uniq_packages =
                   11852: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11853: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11854: 
1.1172.2.99  raeburn  11855:         if (($importedresponses) || ($importedparts)) {
                   11856:             if ($importedparts) {
1.1070    www      11857: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  11858:                 $metaentry{':partorder'}='';
                   11859:                 $metathesekeys{'partorder'}=1;
                   11860:             }
                   11861:             if ($importedresponses) {
                   11862: # We had imported responses and need to rebuild responseorder
                   11863:                 $metaentry{':responseorder'}='';
                   11864:                 $metathesekeys{'responseorder'}=1;
                   11865:             }
                   11866:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   11867:                 my $origid = $origfiletagids[$index+1];
                   11868:                 if ($origfiletagids[$index] eq 'part') {
                   11869: # Original part, part of the problem
                   11870:                     if ($importedparts) {
                   11871:                         $metaentry{':partorder'}.=','.$origid;
                   11872:                     }
                   11873:                 } elsif ($origfiletagids[$index] eq 'import') {
                   11874:                     if ($importedparts) {
                   11875: # We have imported parts at this position
                   11876:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   11877:                     }
                   11878:                     if ($importedresponses) {
                   11879: # We have imported responses at this position
                   11880:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   11881:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   11882:                         }
                   11883:                     }
                   11884:                 } else {
                   11885: # Original response item, part of the problem
                   11886:                     if ($importedresponses) {
                   11887:                         $metaentry{':responseorder'}.=','.$origid;
                   11888:                     }
                   11889:                 }
                   11890:             }
                   11891:             if ($importedparts) {
                   11892:                 $metaentry{':partorder'}=~s/^\,//;
                   11893:             }
                   11894:             if ($importedresponses) {
                   11895:                 $metaentry{':responseorder'}=~s/^\,//;
                   11896:             }
1.1070    www      11897:         }
                   11898: 
1.737     albertel 11899: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11900: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  11901: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11902: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11903: # this is the end of "was not already recently cached
1.71      www      11904:     }
1.599     albertel 11905:     return $metaentry{':'.$what};
1.261     albertel 11906: }
                   11907: 
1.488     albertel 11908: sub metadata_create_package_def {
1.483     albertel 11909:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11910:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11911:     if ($subp eq 'default') { next; }
                   11912:     
1.599     albertel 11913:     if (defined($metaentry{':packages'})) {
                   11914: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11915:     } else {
1.599     albertel 11916: 	$metaentry{':packages'}=$package;
1.483     albertel 11917:     }
                   11918:     my $value=$packagetab{$key};
                   11919:     my $unikey;
                   11920:     $unikey='parameter_0_'.$name;
1.599     albertel 11921:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11922:     $$metathesekeys{$unikey}=1;
1.599     albertel 11923:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11924: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11925:     }
1.599     albertel 11926:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11927: 	$metaentry{':'.$unikey}=
                   11928: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11929:     }
                   11930: }
                   11931: 
1.261     albertel 11932: sub metadata_generate_part0 {
                   11933:     my ($metadata,$metacache,$uri) = @_;
                   11934:     my %allnames;
1.737     albertel 11935:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11936: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11937: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11938: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11939: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11940: 	    $allnames{$name}=$part;
                   11941: 	  }
                   11942: 	}
                   11943:     }
                   11944:     foreach my $name (keys(%allnames)) {
                   11945:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11946:       my $key=":parameter_0_$name";
1.261     albertel 11947:       $$metacache{"$key.part"}='0';
                   11948:       $$metacache{"$key.name"}=$name;
1.428     albertel 11949:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11950: 					   $allnames{$name}.'_'.$name.
                   11951: 					   '.type'};
1.428     albertel 11952:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11953: 			     '.display'};
1.644     www      11954:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11955:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11956:       $$metacache{"$key.display"}=$olddis;
                   11957:     }
1.71      www      11958: }
                   11959: 
1.764     albertel 11960: # ------------------------------------------------------ Devalidate title cache
                   11961: 
                   11962: sub devalidate_title_cache {
                   11963:     my ($url)=@_;
                   11964:     if (!$env{'request.course.id'}) { return; }
                   11965:     my $symb=&symbread($url);
                   11966:     if (!$symb) { return; }
                   11967:     my $key=$env{'request.course.id'}."\0".$symb;
                   11968:     &devalidate_cache_new('title',$key);
                   11969: }
                   11970: 
1.1014    droeschl 11971: # ------------------------------------------------- Get the title of a course
                   11972: 
                   11973: sub current_course_title {
                   11974:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11975: }
1.301     www      11976: # ------------------------------------------------- Get the title of a resource
                   11977: 
                   11978: sub gettitle {
                   11979:     my $urlsymb=shift;
                   11980:     my $symb=&symbread($urlsymb);
1.534     albertel 11981:     if ($symb) {
1.620     albertel 11982: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11983: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11984: 	if (defined($cached)) { 
                   11985: 	    return $result;
                   11986: 	}
1.534     albertel 11987: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11988: 	my $title='';
1.907     albertel 11989: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11990: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11991: 	} else {
                   11992: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11993: 		    &GDBM_READER(),0640)) {
                   11994: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11995: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11996: 		untie(%bighash);
                   11997: 	    }
1.534     albertel 11998: 	}
                   11999: 	$title=~s/\&colon\;/\:/gs;
                   12000: 	if ($title) {
1.1159    www      12001: # Remember both $symb and $title for dynamic metadata
                   12002:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12003:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12004: # Cache this title and then return it
1.599     albertel 12005: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12006: 	}
                   12007: 	$urlsymb=$url;
                   12008:     }
                   12009:     my $title=&metadata($urlsymb,'title');
                   12010:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12011:     return $title;
1.301     www      12012: }
1.613     albertel 12013: 
1.614     albertel 12014: sub get_slot {
                   12015:     my ($which,$cnum,$cdom)=@_;
                   12016:     if (!$cnum || !$cdom) {
1.790     albertel 12017: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12018: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12019: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12020:     }
1.703     albertel 12021:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12022:     my %slotinfo;
                   12023:     if (exists($remembered{$key})) {
                   12024: 	$slotinfo{$which} = $remembered{$key};
                   12025:     } else {
                   12026: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12027: 	&Apache::lonhomework::showhash(%slotinfo);
                   12028: 	my ($tmp)=keys(%slotinfo);
                   12029: 	if ($tmp=~/^error:/) { return (); }
                   12030: 	$remembered{$key} = $slotinfo{$which};
                   12031:     }
1.616     albertel 12032:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12033: 	return %{$slotinfo{$which}};
                   12034:     }
                   12035:     return $slotinfo{$which};
1.614     albertel 12036: }
1.1150    raeburn  12037: 
                   12038: sub get_reservable_slots {
                   12039:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12040:     my $now = time;
                   12041:     my $reservable_info;
                   12042:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12043:     if (exists($remembered{$key})) {
                   12044:         $reservable_info = $remembered{$key};
                   12045:     } else {
                   12046:         my %resv;
                   12047:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12048:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12049:         $reservable_info = \%resv;
                   12050:         $remembered{$key} = $reservable_info;
                   12051:     }
                   12052:     return $reservable_info;
                   12053: }
                   12054: 
                   12055: sub get_course_slots {
                   12056:     my ($cnum,$cdom) = @_;
                   12057:     my $hashid=$cnum.':'.$cdom;
                   12058:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12059:     if (defined($cached)) {
                   12060:         if (ref($result) eq 'HASH') {
                   12061:             return %{$result};
                   12062:         }
                   12063:     } else {
                   12064:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12065:         my ($tmp) = keys(%slots);
                   12066:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12067:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12068:             return %slots;
                   12069:         }
                   12070:     }
                   12071:     return;
                   12072: }
                   12073: 
                   12074: sub devalidate_slots_cache {
                   12075:     my ($cnum,$cdom)=@_;
                   12076:     my $hashid=$cnum.':'.$cdom;
                   12077:     &devalidate_cache_new('allslots',$hashid);
                   12078: }
                   12079: 
1.1172.2.8  raeburn  12080: sub get_coursechange {
                   12081:     my ($cdom,$cnum) = @_;
                   12082:     if ($cdom eq '' || $cnum eq '') {
                   12083:         return unless ($env{'request.course.id'});
                   12084:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12085:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12086:     }
                   12087:     my $hashid=$cdom.'_'.$cnum;
                   12088:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12089:     if ((defined($cached)) && ($change ne '')) {
                   12090:         return $change;
                   12091:     } else {
                   12092:         my %crshash;
                   12093:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12094:         if ($crshash{'internal.contentchange'} eq '') {
                   12095:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12096:             if ($change eq '') {
                   12097:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12098:                 $change = $crshash{'internal.created'};
                   12099:             }
                   12100:         } else {
                   12101:             $change = $crshash{'internal.contentchange'};
                   12102:         }
                   12103:         my $cachetime = 600;
                   12104:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12105:     }
                   12106:     return $change;
                   12107: }
                   12108: 
                   12109: sub devalidate_coursechange_cache {
                   12110:     my ($cnum,$cdom)=@_;
                   12111:     my $hashid=$cnum.':'.$cdom;
                   12112:     &devalidate_cache_new('crschange',$hashid);
                   12113: }
                   12114: 
1.31      www      12115: # ------------------------------------------------- Update symbolic store links
                   12116: 
                   12117: sub symblist {
                   12118:     my ($mapname,%newhash)=@_;
1.438     www      12119:     $mapname=&deversion(&declutter($mapname));
1.31      www      12120:     my %hash;
1.620     albertel 12121:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12122:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12123:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12124: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12125: 		next if ($url eq 'last_known'
                   12126: 			 && $env{'form.no_update_last_known'});
                   12127: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12128: 						    $newhash{$url}->[1],
                   12129: 						    $newhash{$url}->[0]);
1.191     harris41 12130:             }
1.31      www      12131:             if (untie(%hash)) {
                   12132: 		return 'ok';
                   12133:             }
                   12134:         }
                   12135:     }
                   12136:     return 'error';
1.212     www      12137: }
                   12138: 
                   12139: # --------------------------------------------------------------- Verify a symb
                   12140: 
                   12141: sub symbverify {
1.1172.2.11  raeburn  12142:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12143:     my $thisfn=$thisurl;
1.439     www      12144:     $thisfn=&declutter($thisfn);
1.215     www      12145: # direct jump to resource in page or to a sequence - will construct own symbs
                   12146:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12147: # check URL part
1.409     www      12148:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12149: 
1.431     www      12150:     unless ($url eq $thisfn) { return 0; }
1.213     www      12151: 
1.216     www      12152:     $symb=&symbclean($symb);
1.510     www      12153:     $thisurl=&deversion($thisurl);
1.439     www      12154:     $thisfn=&deversion($thisfn);
1.213     www      12155: 
                   12156:     my %bighash;
                   12157:     my $okay=0;
1.431     www      12158: 
1.620     albertel 12159:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12160:                             &GDBM_READER(),0640)) {
1.1172.2.13  raeburn  12161:         my $noclutter;
1.1032    raeburn  12162:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12163:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12164:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12165:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12166:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12167:                 $noclutter = 1;
                   12168:             }
                   12169:         }
                   12170:         my $ids;
                   12171:         if ($noclutter) {
                   12172:             $ids=$bighash{'ids_'.$thisurl};
                   12173:         } else {
                   12174:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12175:         }
1.1102    raeburn  12176:         unless ($ids) {
1.1172.2.13  raeburn  12177:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12178:             $ids=$bighash{$idkey};
1.216     www      12179:         }
                   12180:         if ($ids) {
                   12181: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12182:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12183:                 $symb =~ s/\?.+$//;
                   12184:             }
1.800     albertel 12185: 	    foreach my $id (split(/\,/,$ids)) {
                   12186: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12187:                if (
                   12188:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12189:    eq $symb) {
1.1172.2.11  raeburn  12190:                    if (ref($encstate)) {
                   12191:                        $$encstate = $bighash{'encrypted_'.$id};
                   12192:                    }
1.1172.2.13  raeburn  12193:                    if (($env{'request.role.adv'}) ||
                   12194:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12195:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12196:                        $okay=1;
                   12197:                        last;
                   12198:                    }
                   12199:                }
                   12200:            }
1.216     www      12201:         }
1.213     www      12202: 	untie(%bighash);
                   12203:     }
                   12204:     return $okay;
1.31      www      12205: }
                   12206: 
1.210     www      12207: # --------------------------------------------------------------- Clean-up symb
                   12208: 
                   12209: sub symbclean {
                   12210:     my $symb=shift;
1.568     albertel 12211:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12212: # remove version from map
                   12213:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12214: 
1.210     www      12215: # remove version from URL
                   12216:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12217: 
1.507     www      12218: # remove wrapper
                   12219: 
1.510     www      12220:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12221:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12222:     return $symb;
1.409     www      12223: }
                   12224: 
                   12225: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12226: 
                   12227: sub encode_symb {
                   12228:     my ($map,$resid,$url)=@_;
                   12229:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12230: }
1.409     www      12231: 
                   12232: sub decode_symb {
1.568     albertel 12233:     my $symb=shift;
                   12234:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12235:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12236:     return (&fixversion($map),$resid,&fixversion($url));
                   12237: }
                   12238: 
                   12239: sub fixversion {
                   12240:     my $fn=shift;
1.609     banghart 12241:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12242:     my %bighash;
                   12243:     my $uri=&clutter($fn);
1.620     albertel 12244:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12245: # is this cached?
1.599     albertel 12246:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12247:     if (defined($cached)) { return $result; }
                   12248: # unfortunately not cached, or expired
1.620     albertel 12249:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12250: 	    &GDBM_READER(),0640)) {
                   12251:  	if ($bighash{'version_'.$uri}) {
                   12252:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12253:  	    unless (($version eq 'mostrecent') || 
                   12254: 		    ($version==&getversion($uri))) {
1.440     www      12255:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12256:  	    }
                   12257:  	}
                   12258:  	untie %bighash;
1.413     www      12259:     }
1.599     albertel 12260:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12261: }
                   12262: 
                   12263: sub deversion {
                   12264:     my $url=shift;
                   12265:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12266:     return $url;
1.210     www      12267: }
                   12268: 
1.31      www      12269: # ------------------------------------------------------ Return symb list entry
                   12270: 
                   12271: sub symbread {
1.1172.2.66  raeburn  12272:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12273:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12274:     if (defined($env{$cache_str})) {
                   12275:         if ($ignorecachednull) {
                   12276:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12277:         } else {
                   12278:             return $env{$cache_str};
                   12279:         }
                   12280:     }
1.242     www      12281: # no filename provided? try from environment
1.1172.2.54  raeburn  12282:     unless ($thisfn) {
1.620     albertel 12283:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12284:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12285:         }
                   12286:         $thisfn=$env{'request.filename'};
1.44      www      12287:     }
1.569     albertel 12288:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12289: # is that filename actually a symb? Verify, clean, and return
                   12290:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12291: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12292: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12293: 	}
1.242     www      12294:     }
1.44      www      12295:     $thisfn=declutter($thisfn);
1.31      www      12296:     my %hash;
1.37      www      12297:     my %bighash;
                   12298:     my $syval='';
1.620     albertel 12299:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12300:         my $targetfn = $thisfn;
1.609     banghart 12301:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12302:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12303:         }
1.687     albertel 12304: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12305: 	    $targetfn=$1;
                   12306: 	}
1.620     albertel 12307:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12308:                       &GDBM_READER(),0640)) {
1.481     raeburn  12309: 	    $syval=$hash{$targetfn};
1.37      www      12310:             untie(%hash);
                   12311:         }
                   12312: # ---------------------------------------------------------- There was an entry
                   12313:         if ($syval) {
1.601     albertel 12314: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12315: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12316: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12317: 		    #return $env{$cache_str}='';
1.601     albertel 12318: 		#}    
                   12319: 		#$syval.=$1;
                   12320: 	    #}
1.37      www      12321:         } else {
                   12322: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12323:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12324:                             &GDBM_READER(),0640)) {
1.37      www      12325: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12326:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12327:               unless ($ids) { 
                   12328:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12329:               }
                   12330:               unless ($ids) {
                   12331: # alias?
                   12332: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12333:               }
1.37      www      12334:               if ($ids) {
                   12335: # ------------------------------------------------------------------- Has ID(s)
                   12336:                  my @possibilities=split(/\,/,$ids);
1.39      www      12337:                  if ($#possibilities==0) {
                   12338: # ----------------------------------------------- There is only one possibility
1.37      www      12339: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12340: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12341: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12342:                      if (ref($possibles) eq 'HASH') {
                   12343:                          $possibles->{$syval} = 1;
                   12344:                      }
                   12345:                      if ($checkforblock) {
                   12346:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12347:                          if (@blockers) {
                   12348:                              $syval = '';
                   12349:                              return;
                   12350:                          }
                   12351:                      }
                   12352:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12353: # ------------------------------------------ There is more than one possibility
                   12354:                      my $realpossible=0;
1.800     albertel 12355:                      foreach my $id (@possibilities) {
                   12356: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12357:                          my $canaccess;
                   12358:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12359:                              $canaccess = 1;
                   12360:                          } else {
                   12361:                              $canaccess = &allowed('bre',$file);
                   12362:                          }
                   12363:                          if ($canaccess) {
                   12364:          		     my ($mapid,$resid)=split(/\./,$id);
                   12365:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12366:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12367:                                                              $resid,$thisfn);
                   12368:                                  if (ref($possibles) eq 'HASH') {
                   12369:                                      $possibles->{$syval} = 1;
                   12370:                                  }
                   12371:                                  if ($checkforblock) {
                   12372:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12373:                                      unless (@blockers > 0) {
                   12374:                                          $syval = $poss_syval;
                   12375:                                          $realpossible++;
                   12376:                                      }
                   12377:                                  } else {
                   12378:                                      $syval = $poss_syval;
                   12379:                                      $realpossible++;
                   12380:                                  }
                   12381:                              }
1.39      www      12382: 			 }
1.191     harris41 12383:                      }
1.39      www      12384: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12385:                  } else {
                   12386:                      $syval='';
1.37      www      12387:                  }
                   12388: 	      }
1.1172.2.66  raeburn  12389:               untie(%bighash);
1.481     raeburn  12390:            }
1.31      www      12391:         }
1.62      www      12392:         if ($syval) {
1.620     albertel 12393: 	    return $env{$cache_str}=$syval;
1.62      www      12394:         }
1.31      www      12395:     }
1.949     raeburn  12396:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12397:     return $env{$cache_str}='';
1.31      www      12398: }
                   12399: 
                   12400: # ---------------------------------------------------------- Return random seed
                   12401: 
1.32      www      12402: sub numval {
                   12403:     my $txt=shift;
                   12404:     $txt=~tr/A-J/0-9/;
                   12405:     $txt=~tr/a-j/0-9/;
                   12406:     $txt=~tr/K-T/0-9/;
                   12407:     $txt=~tr/k-t/0-9/;
                   12408:     $txt=~tr/U-Z/0-5/;
                   12409:     $txt=~tr/u-z/0-5/;
                   12410:     $txt=~s/\D//g;
1.564     albertel 12411:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12412:     return int($txt);
1.368     albertel 12413: }
                   12414: 
1.484     albertel 12415: sub numval2 {
                   12416:     my $txt=shift;
                   12417:     $txt=~tr/A-J/0-9/;
                   12418:     $txt=~tr/a-j/0-9/;
                   12419:     $txt=~tr/K-T/0-9/;
                   12420:     $txt=~tr/k-t/0-9/;
                   12421:     $txt=~tr/U-Z/0-5/;
                   12422:     $txt=~tr/u-z/0-5/;
                   12423:     $txt=~s/\D//g;
                   12424:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12425:     my $total;
                   12426:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12427:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12428:     return int($total);
                   12429: }
                   12430: 
1.575     albertel 12431: sub numval3 {
                   12432:     use integer;
                   12433:     my $txt=shift;
                   12434:     $txt=~tr/A-J/0-9/;
                   12435:     $txt=~tr/a-j/0-9/;
                   12436:     $txt=~tr/K-T/0-9/;
                   12437:     $txt=~tr/k-t/0-9/;
                   12438:     $txt=~tr/U-Z/0-5/;
                   12439:     $txt=~tr/u-z/0-5/;
                   12440:     $txt=~s/\D//g;
                   12441:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12442:     my $total;
                   12443:     foreach my $val (@txts) { $total+=$val; }
                   12444:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12445:     return $total;
                   12446: }
                   12447: 
1.675     albertel 12448: sub digest {
                   12449:     my ($data)=@_;
                   12450:     my $digest=&Digest::MD5::md5($data);
                   12451:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12452:     my ($e,$f);
                   12453:     {
                   12454:         use integer;
                   12455:         $e=($a+$b);
                   12456:         $f=($c+$d);
                   12457:         if ($_64bit) {
                   12458:             $e=(($e<<32)>>32);
                   12459:             $f=(($f<<32)>>32);
                   12460:         }
                   12461:     }
                   12462:     if (wantarray) {
                   12463: 	return ($e,$f);
                   12464:     } else {
                   12465: 	my $g;
                   12466: 	{
                   12467: 	    use integer;
                   12468: 	    $g=($e+$f);
                   12469: 	    if ($_64bit) {
                   12470: 		$g=(($g<<32)>>32);
                   12471: 	    }
                   12472: 	}
                   12473: 	return $g;
                   12474:     }
                   12475: }
                   12476: 
1.368     albertel 12477: sub latest_rnd_algorithm_id {
1.675     albertel 12478:     return '64bit5';
1.366     albertel 12479: }
1.32      www      12480: 
1.503     albertel 12481: sub get_rand_alg {
                   12482:     my ($courseid)=@_;
1.790     albertel 12483:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12484:     if ($courseid) {
1.620     albertel 12485: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12486:     }
                   12487:     return &latest_rnd_algorithm_id();
                   12488: }
                   12489: 
1.562     albertel 12490: sub validCODE {
                   12491:     my ($CODE)=@_;
                   12492:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12493:     return 0;
                   12494: }
                   12495: 
1.491     albertel 12496: sub getCODE {
1.620     albertel 12497:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12498:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12499: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12500: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12501: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12502:     }
                   12503:     return undef;
                   12504: }
1.1133    foxr     12505: #
                   12506: #  Determines the random seed for a specific context:
                   12507: #
                   12508: # parameters:
                   12509: #   symb      - in course context the symb for the seed.
                   12510: #   course_id - The course id of the form domain_coursenum.
                   12511: #   domain    - Domain for the user.
                   12512: #   course    - Course for the user.
                   12513: #   cenv      - environment of the course.
                   12514: #
                   12515: # NOTE:
                   12516: #   All parameters are picked out of the environment if missing
                   12517: #   or not defined.
                   12518: #   If a symb cannot be determined the current time is used instead.
                   12519: #
                   12520: #  For a given well defined symb, courside, domain, username,
                   12521: #  and course environment, the seed is reproducible.
                   12522: #
1.31      www      12523: sub rndseed {
1.1133    foxr     12524:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12525:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12526:     if (!defined($symb)) {
1.366     albertel 12527: 	unless ($symb=$wsymb) { return time; }
                   12528:     }
1.1146    foxr     12529:     if (!defined $courseid) { 
                   12530: 	$courseid=$wcourseid; 
                   12531:     }
                   12532:     if (!defined $domain) { $domain=$wdomain; }
                   12533:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12534: 
                   12535:     my $which;
                   12536:     if (defined($cenv->{'rndseed'})) {
                   12537: 	$which = $cenv->{'rndseed'};
                   12538:     } else {
                   12539: 	$which =&get_rand_alg($courseid);
                   12540:     }
1.491     albertel 12541:     if (defined(&getCODE())) {
1.675     albertel 12542: 	if ($which eq '64bit5') {
                   12543: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12544: 	} elsif ($which eq '64bit4') {
1.575     albertel 12545: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12546: 	} else {
                   12547: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12548: 	}
1.675     albertel 12549:     } elsif ($which eq '64bit5') {
                   12550: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12551:     } elsif ($which eq '64bit4') {
                   12552: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12553:     } elsif ($which eq '64bit3') {
                   12554: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12555:     } elsif ($which eq '64bit2') {
                   12556: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12557:     } elsif ($which eq '64bit') {
                   12558: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12559:     }
                   12560:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12561: }
                   12562: 
                   12563: sub rndseed_32bit {
                   12564:     my ($symb,$courseid,$domain,$username)=@_;
                   12565:     {
                   12566: 	use integer;
                   12567: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12568: 	my $symbseed=numval($symb) << 22;
                   12569: 	my $namechck=unpack("%32C*",$username) << 17;
                   12570: 	my $nameseed=numval($username) << 12;
                   12571: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12572: 	my $courseseed=unpack("%32C*",$courseid);
                   12573: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12574: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12575: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12576: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12577: 	return $num;
                   12578:     }
                   12579: }
                   12580: 
                   12581: sub rndseed_64bit {
                   12582:     my ($symb,$courseid,$domain,$username)=@_;
                   12583:     {
                   12584: 	use integer;
                   12585: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12586: 	my $symbseed=numval($symb) << 10;
                   12587: 	my $namechck=unpack("%32S*",$username);
                   12588: 	
                   12589: 	my $nameseed=numval($username) << 21;
                   12590: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12591: 	my $courseseed=unpack("%32S*",$courseid);
                   12592: 	
                   12593: 	my $num1=$symbchck+$symbseed+$namechck;
                   12594: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12595: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12596: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12597: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12598: 	return "$num1,$num2";
1.155     albertel 12599:     }
1.366     albertel 12600: }
                   12601: 
1.443     albertel 12602: sub rndseed_64bit2 {
                   12603:     my ($symb,$courseid,$domain,$username)=@_;
                   12604:     {
                   12605: 	use integer;
                   12606: 	# strings need to be an even # of cahracters long, it it is odd the
                   12607:         # last characters gets thrown away
                   12608: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12609: 	my $symbseed=numval($symb) << 10;
                   12610: 	my $namechck=unpack("%32S*",$username.' ');
                   12611: 	
                   12612: 	my $nameseed=numval($username) << 21;
1.501     albertel 12613: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12614: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12615: 	
                   12616: 	my $num1=$symbchck+$symbseed+$namechck;
                   12617: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12618: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12619: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12620: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12621: 	return "$num1,$num2";
                   12622:     }
                   12623: }
                   12624: 
                   12625: sub rndseed_64bit3 {
                   12626:     my ($symb,$courseid,$domain,$username)=@_;
                   12627:     {
                   12628: 	use integer;
                   12629: 	# strings need to be an even # of cahracters long, it it is odd the
                   12630:         # last characters gets thrown away
                   12631: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12632: 	my $symbseed=numval2($symb) << 10;
                   12633: 	my $namechck=unpack("%32S*",$username.' ');
                   12634: 	
                   12635: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12636: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12637: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12638: 	
                   12639: 	my $num1=$symbchck+$symbseed+$namechck;
                   12640: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12641: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12642: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12643: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12644: 	
1.503     albertel 12645: 	return "$num1:$num2";
1.443     albertel 12646:     }
                   12647: }
                   12648: 
1.575     albertel 12649: sub rndseed_64bit4 {
                   12650:     my ($symb,$courseid,$domain,$username)=@_;
                   12651:     {
                   12652: 	use integer;
                   12653: 	# strings need to be an even # of cahracters long, it it is odd the
                   12654:         # last characters gets thrown away
                   12655: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12656: 	my $symbseed=numval3($symb) << 10;
                   12657: 	my $namechck=unpack("%32S*",$username.' ');
                   12658: 	
                   12659: 	my $nameseed=numval3($username) << 21;
                   12660: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12661: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12662: 	
                   12663: 	my $num1=$symbchck+$symbseed+$namechck;
                   12664: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12665: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12666: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12667: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12668: 	
1.575     albertel 12669: 	return "$num1:$num2";
                   12670:     }
                   12671: }
                   12672: 
1.675     albertel 12673: sub rndseed_64bit5 {
                   12674:     my ($symb,$courseid,$domain,$username)=@_;
                   12675:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12676:     return "$num1:$num2";
                   12677: }
                   12678: 
1.366     albertel 12679: sub rndseed_CODE_64bit {
                   12680:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12681:     {
1.366     albertel 12682: 	use integer;
1.443     albertel 12683: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12684: 	my $symbseed=numval2($symb);
1.491     albertel 12685: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12686: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12687: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12688: 	my $num1=$symbseed+$CODEchck;
                   12689: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12690: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12691: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12692: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12693: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12694: 	return "$num1:$num2";
1.366     albertel 12695:     }
                   12696: }
                   12697: 
1.575     albertel 12698: sub rndseed_CODE_64bit4 {
                   12699:     my ($symb,$courseid,$domain,$username)=@_;
                   12700:     {
                   12701: 	use integer;
                   12702: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12703: 	my $symbseed=numval3($symb);
                   12704: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12705: 	my $CODEseed=numval3(&getCODE());
                   12706: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12707: 	my $num1=$symbseed+$CODEchck;
                   12708: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12709: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12710: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12711: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12712: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12713: 	return "$num1:$num2";
                   12714:     }
                   12715: }
                   12716: 
1.675     albertel 12717: sub rndseed_CODE_64bit5 {
                   12718:     my ($symb,$courseid,$domain,$username)=@_;
                   12719:     my $code = &getCODE();
                   12720:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12721:     return "$num1:$num2";
                   12722: }
                   12723: 
1.366     albertel 12724: sub setup_random_from_rndseed {
                   12725:     my ($rndseed)=@_;
1.503     albertel 12726:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12727: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12728:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12729:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12730:         } else {
                   12731:             &Math::Random::random_set_seed($num1,$num2);
                   12732:         }
1.366     albertel 12733:     } else {
                   12734: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12735:     }
1.36      albertel 12736: }
                   12737: 
1.474     albertel 12738: sub latest_receipt_algorithm_id {
1.835     albertel 12739:     return 'receipt3';
1.474     albertel 12740: }
                   12741: 
1.480     www      12742: sub recunique {
                   12743:     my $fucourseid=shift;
                   12744:     my $unique;
1.835     albertel 12745:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12746: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12747: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12748:     } else {
                   12749: 	$unique=$perlvar{'lonReceipt'};
                   12750:     }
                   12751:     return unpack("%32C*",$unique);
                   12752: }
                   12753: 
                   12754: sub recprefix {
                   12755:     my $fucourseid=shift;
                   12756:     my $prefix;
1.835     albertel 12757:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12758: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12759: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12760:     } else {
                   12761: 	$prefix=$perlvar{'lonHostID'};
                   12762:     }
                   12763:     return unpack("%32C*",$prefix);
                   12764: }
                   12765: 
1.76      www      12766: sub ireceipt {
1.474     albertel 12767:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12768: 
                   12769:     my $return =&recprefix($fucourseid).'-';
                   12770: 
                   12771:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12772: 	$env{'request.state'} eq 'construct') {
                   12773: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12774: 	return $return;
                   12775:     }
                   12776: 
1.76      www      12777:     my $cuname=unpack("%32C*",$funame);
                   12778:     my $cudom=unpack("%32C*",$fudom);
                   12779:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12780:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12781:     my $cunique=&recunique($fucourseid);
1.474     albertel 12782:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12783:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12784: 
1.790     albertel 12785: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12786: 			       
                   12787: 	$return.= ($cunique%$cuname+
                   12788: 		   $cunique%$cudom+
                   12789: 		   $cusymb%$cuname+
                   12790: 		   $cusymb%$cudom+
                   12791: 		   $cucourseid%$cuname+
                   12792: 		   $cucourseid%$cudom+
                   12793: 		   $cpart%$cuname+
                   12794: 		   $cpart%$cudom);
                   12795:     } else {
                   12796: 	$return.= ($cunique%$cuname+
                   12797: 		   $cunique%$cudom+
                   12798: 		   $cusymb%$cuname+
                   12799: 		   $cusymb%$cudom+
                   12800: 		   $cucourseid%$cuname+
                   12801: 		   $cucourseid%$cudom);
                   12802:     }
                   12803:     return $return;
1.76      www      12804: }
                   12805: 
                   12806: sub receipt {
1.474     albertel 12807:     my ($part)=@_;
1.790     albertel 12808:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12809:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12810: }
1.260     ng       12811: 
1.790     albertel 12812: sub whichuser {
                   12813:     my ($passedsymb)=@_;
                   12814:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12815:     if (defined($env{'form.grade_symb'})) {
                   12816: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12817: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12818: 	if (!$allowed &&
                   12819: 	    exists($env{'request.course.sec'}) &&
                   12820: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12821: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12822: 			      '/'.$env{'request.course.sec'});
                   12823: 	}
                   12824: 	if ($allowed) {
                   12825: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12826: 	    $courseid=$tmp_courseid;
                   12827: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12828: 	    ($name)=&get_env_multiple('form.grade_username');
                   12829: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12830: 	}
                   12831:     }
                   12832:     if (!$passedsymb) {
                   12833: 	$symb=&symbread();
                   12834:     } else {
                   12835: 	$symb=$passedsymb;
                   12836:     }
                   12837:     $courseid=$env{'request.course.id'};
                   12838:     $domain=$env{'user.domain'};
                   12839:     $name=$env{'user.name'};
                   12840:     if ($name eq 'public' && $domain eq 'public') {
                   12841: 	if (!defined($env{'form.username'})) {
                   12842: 	    $env{'form.username'}.=time.rand(10000000);
                   12843: 	}
                   12844: 	$name.=$env{'form.username'};
                   12845:     }
                   12846:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12847: 
                   12848: }
                   12849: 
1.36      albertel 12850: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12851: # returns either the contents of the file or 
                   12852: # -1 if the file doesn't exist
1.481     raeburn  12853: #
                   12854: # if the target is a file that was uploaded via DOCS, 
                   12855: # a check will be made to see if a current copy exists on the local server,
                   12856: # if it does this will be served, otherwise a copy will be retrieved from
                   12857: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12858: # the local server.   
1.472     albertel 12859: 
1.36      albertel 12860: sub getfile {
1.538     albertel 12861:     my ($file) = @_;
1.609     banghart 12862:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12863:     &repcopy($file);
                   12864:     return &readfile($file);
                   12865: }
                   12866: 
                   12867: sub repcopy_userfile {
                   12868:     my ($file)=@_;
1.1142    raeburn  12869:     my $londocroot = $perlvar{'lonDocRoot'};
                   12870:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12871:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12872:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12873: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12874:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12875:     if (-e "$file") {
1.828     www      12876: # we already have a local copy, check it out
1.538     albertel 12877: 	my @fileinfo = stat($file);
1.828     www      12878: 	my $rtncode;
                   12879: 	my $info;
1.538     albertel 12880: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12881: 	if ($lwpresp ne 'ok') {
1.828     www      12882: # there is no such file anymore, even though we had a local copy
1.482     albertel 12883: 	    if ($rtncode eq '404') {
1.538     albertel 12884: 		unlink($file);
1.482     albertel 12885: 	    }
                   12886: 	    return -1;
                   12887: 	}
                   12888: 	if ($info < $fileinfo[9]) {
1.828     www      12889: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12890: 	    return 'ok';
1.828     www      12891: 	} else {
                   12892: # the file is outdated, get rid of it
                   12893: 	    unlink($file);
1.482     albertel 12894: 	}
1.828     www      12895:     }
                   12896: # one way or the other, at this point, we don't have the file
                   12897: # construct the correct path for the file
                   12898:     my @parts = ($cdom,$cnum); 
                   12899:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12900: 	push @parts, split(/\//,$1);
                   12901:     }
                   12902:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12903:     foreach my $part (@parts) {
                   12904: 	$path .= '/'.$part;
                   12905: 	if (!-e $path) {
                   12906: 	    mkdir($path,0770);
1.482     albertel 12907: 	}
                   12908:     }
1.828     www      12909: # now the path exists for sure
                   12910: # get a user agent
                   12911:     my $ua=new LWP::UserAgent;
                   12912:     my $transferfile=$file.'.in.transfer';
                   12913: # FIXME: this should flock
                   12914:     if (-e $transferfile) { return 'ok'; }
                   12915:     my $request;
                   12916:     $uri=~s/^\///;
1.980     raeburn  12917:     my $homeserver = &homeserver($cnum,$cdom);
                   12918:     my $protocol = $protocol{$homeserver};
                   12919:     $protocol = 'http' if ($protocol ne 'https');
                   12920:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12921:     my $response=$ua->request($request,$transferfile);
                   12922: # did it work?
                   12923:     if ($response->is_error()) {
                   12924: 	unlink($transferfile);
                   12925: 	&logthis("Userfile repcopy failed for $uri");
                   12926: 	return -1;
                   12927:     }
                   12928: # worked, rename the transfer file
                   12929:     rename($transferfile,$file);
1.607     raeburn  12930:     return 'ok';
1.481     raeburn  12931: }
                   12932: 
1.517     albertel 12933: sub tokenwrapper {
                   12934:     my $uri=shift;
1.980     raeburn  12935:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12936:     $uri=~s|^/||;
1.620     albertel 12937:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12938:     my $token=$1;
1.552     albertel 12939:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12940:     if ($udom && $uname && $file) {
                   12941: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12942:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12943:         my $homeserver = &homeserver($uname,$udom);
                   12944:         my $protocol = $protocol{$homeserver};
                   12945:         $protocol = 'http' if ($protocol ne 'https');
                   12946:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12947:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12948:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12949:     } else {
                   12950:         return '/adm/notfound.html';
                   12951:     }
                   12952: }
                   12953: 
1.828     www      12954: # call with reqtype HEAD: get last modification time
                   12955: # call with reqtype GET: get the file contents
                   12956: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12957: #
1.481     raeburn  12958: sub getuploaded {
                   12959:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12960:     $uri=~s/^\///;
1.980     raeburn  12961:     my $homeserver = &homeserver($cnum,$cdom);
                   12962:     my $protocol = $protocol{$homeserver};
                   12963:     $protocol = 'http' if ($protocol ne 'https');
                   12964:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12965:     my $ua=new LWP::UserAgent;
                   12966:     my $request=new HTTP::Request($reqtype,$uri);
                   12967:     my $response=$ua->request($request);
                   12968:     $$rtncode = $response->code;
1.482     albertel 12969:     if (! $response->is_success()) {
                   12970: 	return 'failed';
                   12971:     }      
                   12972:     if ($reqtype eq 'HEAD') {
1.486     www      12973: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12974:     } elsif ($reqtype eq 'GET') {
                   12975: 	$$info = $response->content;
1.472     albertel 12976:     }
1.482     albertel 12977:     return 'ok';
1.36      albertel 12978: }
                   12979: 
1.481     raeburn  12980: sub readfile {
                   12981:     my $file = shift;
                   12982:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12983:     my $fh;
1.1172.2.96  raeburn  12984:     open($fh,"<",$file);
1.481     raeburn  12985:     my $a='';
1.800     albertel 12986:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12987:     return $a;
                   12988: }
                   12989: 
1.36      albertel 12990: sub filelocation {
1.590     banghart 12991:     my ($dir,$file) = @_;
                   12992:     my $location;
                   12993:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12994: 
                   12995:     if ($file =~ m-^/adm/-) {
                   12996: 	$file=~s-^/adm/wrapper/-/-;
                   12997: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12998:     }
1.882     albertel 12999: 
1.1139    www      13000:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13001:         $location = $file;
1.609     banghart 13002:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13003:         my ($udom,$uname,$filename)=
1.811     albertel 13004:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13005:         my $home=&homeserver($uname,$udom);
                   13006:         my $is_me=0;
                   13007:         my @ids=&current_machine_ids();
                   13008:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13009:         if ($is_me) {
1.1117    foxr     13010:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13011:         } else {
                   13012:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13013:   	      $udom.'/'.$uname.'/'.$filename;
                   13014:         }
1.882     albertel 13015:     } elsif ($file =~ m-^/adm/-) {
                   13016: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13017:     } else {
                   13018:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13019:         $file=~s:^/(res|priv)/:/:;
                   13020:         my $space=$1;
1.590     banghart 13021:         if ( !( $file =~ m:^/:) ) {
                   13022:             $location = $dir. '/'.$file;
                   13023:         } else {
1.1142    raeburn  13024:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13025:         }
1.59      albertel 13026:     }
1.590     banghart 13027:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13028:     while ($location=~m{/\.\./}) {
                   13029: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13030: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13031: 	} else {
                   13032: 	    $location=~ s{/\.\./}{/}g;
                   13033: 	}
                   13034:     } #remove dir/..
1.590     banghart 13035:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13036:     return $location;
1.46      www      13037: }
1.36      albertel 13038: 
1.46      www      13039: sub hreflocation {
                   13040:     my ($dir,$file)=@_;
1.980     raeburn  13041:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13042: 	$file=filelocation($dir,$file);
1.700     albertel 13043:     } elsif ($file=~m-^/adm/-) {
                   13044: 	$file=~s-^/adm/wrapper/-/-;
                   13045: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13046:     }
                   13047:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13048: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13049:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13050: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13051: 	        {/uploaded/$1/$2/}x;
1.46      www      13052:     }
1.913     albertel 13053:     if ($file=~ m{^/userfiles/}) {
                   13054: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13055:     }
1.462     albertel 13056:     return $file;
1.465     albertel 13057: }
                   13058: 
1.1139    www      13059: 
                   13060: 
                   13061: 
                   13062: 
1.465     albertel 13063: sub current_machine_domains {
1.853     albertel 13064:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13065: }
                   13066: 
                   13067: sub machine_domains {
                   13068:     my ($hostname) = @_;
1.465     albertel 13069:     my @domains;
1.838     albertel 13070:     my %hostname = &all_hostnames();
1.465     albertel 13071:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13072: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13073: 	if ($hostname eq $name) {
1.844     albertel 13074: 	    push(@domains,&host_domain($id));
1.465     albertel 13075: 	}
                   13076:     }
                   13077:     return @domains;
                   13078: }
                   13079: 
                   13080: sub current_machine_ids {
1.853     albertel 13081:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13082: }
                   13083: 
                   13084: sub machine_ids {
                   13085:     my ($hostname) = @_;
                   13086:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13087:     my @ids;
1.888     albertel 13088:     my %name_to_host = &all_names();
1.889     albertel 13089:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13090: 	return @{ $name_to_host{$hostname} };
                   13091:     }
                   13092:     return;
1.31      www      13093: }
                   13094: 
1.824     raeburn  13095: sub additional_machine_domains {
                   13096:     my @domains;
1.1172.2.96  raeburn  13097:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13098:     while( my $line = <$fh>) {
                   13099:         $line =~ s/\s//g;
                   13100:         push(@domains,$line);
                   13101:     }
                   13102:     return @domains;
                   13103: }
                   13104: 
                   13105: sub default_login_domain {
                   13106:     my $domain = $perlvar{'lonDefDomain'};
                   13107:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13108:     foreach my $posdom (&current_machine_domains(),
                   13109:                         &additional_machine_domains()) {
                   13110:         if (lc($posdom) eq lc($testdomain)) {
                   13111:             $domain=$posdom;
                   13112:             last;
                   13113:         }
                   13114:     }
                   13115:     return $domain;
                   13116: }
                   13117: 
1.1172.2.106  raeburn  13118: sub shared_institution {
                   13119:     my ($dom) = @_;
                   13120:     my $same_intdom;
                   13121:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13122:     if ($hostintdom ne '') {
                   13123:         my %iphost = &get_iphost();
                   13124:         my $primary_id = &domain($dom,'primary');
                   13125:         my $primary_ip = &get_host_ip($primary_id);
                   13126:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13127:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13128:                 my $intdom = &internet_dom($id);
                   13129:                 if ($intdom eq $hostintdom) {
                   13130:                     $same_intdom = 1;
                   13131:                     last;
                   13132:                 }
                   13133:             }
                   13134:         }
                   13135:     }
                   13136:     return $same_intdom;
                   13137: }
                   13138: 
1.31      www      13139: # ------------------------------------------------------------- Declutters URLs
                   13140: 
                   13141: sub declutter {
                   13142:     my $thisfn=shift;
1.569     albertel 13143:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13144:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13145:         $thisfn=~s{^/home/httpd/html}{};
                   13146:     }
1.31      www      13147:     $thisfn=~s/^\///;
1.697     albertel 13148:     $thisfn=~s|^adm/wrapper/||;
                   13149:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13150:     $thisfn=~s/^res\///;
1.1172    bisitz   13151:     $thisfn=~s/^priv\///;
1.1032    raeburn  13152:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13153:         $thisfn=~s/\?.+$//;
                   13154:     }
1.268     www      13155:     return $thisfn;
                   13156: }
                   13157: 
                   13158: # ------------------------------------------------------------- Clutter up URLs
                   13159: 
                   13160: sub clutter {
                   13161:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13162:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13163: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13164:        $thisfn='/res'.$thisfn; 
                   13165:     }
1.1031    raeburn  13166:     if ($thisfn !~m|^/adm|) {
                   13167: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13168: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13169: 	} else {
                   13170: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13171: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13172: 	    if ($embstyle eq 'ssi'
                   13173: 		|| ($embstyle eq 'hdn')
                   13174: 		|| ($embstyle eq 'rat')
                   13175: 		|| ($embstyle eq 'prv')
                   13176: 		|| ($embstyle eq 'ign')) {
                   13177: 		#do nothing with these
                   13178: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13179: 		|| ($embstyle eq 'emb')
                   13180: 		|| ($embstyle eq 'wrp')) {
                   13181: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13182: 	    } elsif ($embstyle eq 'unk'
                   13183: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13184: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13185: 	    } else {
1.718     www      13186: #		&logthis("Got a blank emb style");
1.695     albertel 13187: 	    }
1.694     albertel 13188: 	}
                   13189:     }
1.31      www      13190:     return $thisfn;
1.12      www      13191: }
                   13192: 
1.787     albertel 13193: sub clutter_with_no_wrapper {
                   13194:     my $uri = &clutter(shift);
                   13195:     if ($uri =~ m-^/adm/-) {
                   13196: 	$uri =~ s-^/adm/wrapper/-/-;
                   13197: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13198:     }
                   13199:     return $uri;
                   13200: }
                   13201: 
1.557     albertel 13202: sub freeze_escape {
                   13203:     my ($value)=@_;
                   13204:     if (ref($value)) {
                   13205: 	$value=&nfreeze($value);
                   13206: 	return '__FROZEN__'.&escape($value);
                   13207:     }
                   13208:     return &escape($value);
                   13209: }
                   13210: 
1.11      www      13211: 
1.557     albertel 13212: sub thaw_unescape {
                   13213:     my ($value)=@_;
                   13214:     if ($value =~ /^__FROZEN__/) {
                   13215: 	substr($value,0,10,undef);
                   13216: 	$value=&unescape($value);
                   13217: 	return &thaw($value);
                   13218:     }
                   13219:     return &unescape($value);
                   13220: }
                   13221: 
1.436     albertel 13222: sub correct_line_ends {
                   13223:     my ($result)=@_;
                   13224:     $$result =~s/\r\n/\n/mg;
                   13225:     $$result =~s/\r/\n/mg;
1.415     albertel 13226: }
1.1       albertel 13227: # ================================================================ Main Program
                   13228: 
1.184     www      13229: sub goodbye {
1.204     albertel 13230:    &logthis("Starting Shut down");
1.443     albertel 13231: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13232:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13233: #converted
1.599     albertel 13234: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13235:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13236: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13237: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13238: #1.1 only
1.870     albertel 13239: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13240: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13241: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13242: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13243:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13244:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13245:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13246:    &flushcourselogs();
                   13247:    &logthis("Shutting down");
                   13248: }
                   13249: 
1.852     albertel 13250: sub get_dns {
1.1172.2.17  raeburn  13251:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13252:     if (!$ignore_cache) {
                   13253: 	my ($content,$cached)=
                   13254: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13255: 	if ($cached) {
1.1172.2.17  raeburn  13256: 	    &$func($content,$hashref);
1.869     albertel 13257: 	    return;
                   13258: 	}
                   13259:     }
                   13260: 
                   13261:     my %alldns;
1.1172.2.96  raeburn  13262:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13263:         foreach my $dns (<$config>) {
                   13264: 	    next if ($dns !~ /^\^(\S*)/x);
                   13265:             my $line = $1;
                   13266:             my ($host,$protocol) = split(/:/,$line);
                   13267:             if ($protocol ne 'https') {
                   13268:                 $protocol = 'http';
                   13269:             }
                   13270: 	    $alldns{$host} = $protocol;
1.979     raeburn  13271:         }
1.1172.2.96  raeburn  13272:         close($config);
1.869     albertel 13273:     }
                   13274:     while (%alldns) {
1.1172.2.52  raeburn  13275: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13276: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13277:         $ua->timeout(30);
1.979     raeburn  13278: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13279: 	my $response=$ua->request($request);
1.979     raeburn  13280:         delete($alldns{$dns});
1.852     albertel 13281: 	next if ($response->is_error());
                   13282: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13283:         unless ($nocache) {
1.1172.2.23  raeburn  13284: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13285:         }
                   13286: 	&$func(\@content,$hashref);
1.869     albertel 13287: 	return;
1.852     albertel 13288:     }
1.871     albertel 13289:     my $which = (split('/',$url))[3];
                   13290:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13291:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13292:         my @content = <$config>;
                   13293:         &$func(\@content,$hashref);
                   13294:     }
1.1172.2.17  raeburn  13295:     return;
                   13296: }
                   13297: 
                   13298: # ------------------------------------------------------Get DNS checksums file
                   13299: sub parse_dns_checksums_tab {
                   13300:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13301:     my $lonhost = $perlvar{'lonHostID'};
                   13302:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13303:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13304:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13305:     my $webconfdir = '/etc/httpd/conf';
                   13306:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13307:         $webconfdir = '/etc/apache2';
                   13308:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13309:         if ($1 >= 10) {
                   13310:             $webconfdir = '/etc/apache2';
                   13311:         }
                   13312:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13313:         if ($1 >= 10.0) {
                   13314:             $webconfdir = '/etc/apache2';
                   13315:         }
                   13316:     }
1.1172.2.17  raeburn  13317:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13318:     my (%chksum,%revnum);
                   13319:     if (ref($lines) eq 'ARRAY') {
                   13320:         chomp(@{$lines});
1.1172.2.34  raeburn  13321:         my $version = shift(@{$lines});
                   13322:         if ($version eq $release) {
1.1172.2.17  raeburn  13323:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13324:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13325:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13326:                     if ($webconfdir eq '/etc/apache2') {
                   13327:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13328:                     }
                   13329:                 }
1.1172.2.34  raeburn  13330:                 $chksum{$file} = $shasum;
                   13331:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13332:             }
                   13333:             if (ref($hashref) eq 'HASH') {
                   13334:                 %{$hashref} = (
                   13335:                                 sums     => \%chksum,
                   13336:                                 versions => \%revnum,
                   13337:                               );
                   13338:             }
                   13339:         }
                   13340:     }
1.869     albertel 13341:     return;
1.852     albertel 13342: }
1.1172.2.17  raeburn  13343: 
                   13344: sub fetch_dns_checksums {
                   13345:     my %checksums;
1.1172.2.34  raeburn  13346:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13347:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13348:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13349:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13350:              \%checksums);
                   13351:     return \%checksums;
                   13352: }
                   13353: 
1.327     albertel 13354: # ------------------------------------------------------------ Read domain file
                   13355: {
1.852     albertel 13356:     my $loaded;
1.846     albertel 13357:     my %domain;
                   13358: 
1.852     albertel 13359:     sub parse_domain_tab {
                   13360: 	my ($lines) = @_;
                   13361: 	foreach my $line (@$lines) {
                   13362: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13363: 
1.846     albertel 13364: 	    chomp($line);
1.852     albertel 13365: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13366: 	    my %this_domain;
                   13367: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13368: 			       'lang_def', 'city', 'longi', 'lati',
                   13369: 			       'primary') {
                   13370: 		$this_domain{$field} = shift(@elements);
                   13371: 	    }
                   13372: 	    $domain{$name} = \%this_domain;
1.852     albertel 13373: 	}
                   13374:     }
1.864     albertel 13375: 
                   13376:     sub reset_domain_info {
                   13377: 	undef($loaded);
                   13378: 	undef(%domain);
                   13379:     }
                   13380: 
1.852     albertel 13381:     sub load_domain_tab {
1.1172.2.70  raeburn  13382: 	my ($ignore_cache,$nocache) = @_;
                   13383: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13384: 	my $fh;
1.1172.2.96  raeburn  13385: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13386: 	    my @lines = <$fh>;
                   13387: 	    &parse_domain_tab(\@lines);
1.448     albertel 13388: 	}
1.852     albertel 13389: 	close($fh);
                   13390: 	$loaded = 1;
1.327     albertel 13391:     }
1.846     albertel 13392: 
                   13393:     sub domain {
1.852     albertel 13394: 	&load_domain_tab() if (!$loaded);
                   13395: 
1.846     albertel 13396: 	my ($name,$what) = @_;
                   13397: 	return if ( !exists($domain{$name}) );
                   13398: 
                   13399: 	if (!$what) {
                   13400: 	    return $domain{$name}{'description'};
                   13401: 	}
                   13402: 	return $domain{$name}{$what};
                   13403:     }
1.974     raeburn  13404: 
                   13405:     sub domain_info {
                   13406:         &load_domain_tab() if (!$loaded);
                   13407:         return %domain;
                   13408:     }
                   13409: 
1.327     albertel 13410: }
                   13411: 
                   13412: 
1.1       albertel 13413: # ------------------------------------------------------------- Read hosts file
                   13414: {
1.838     albertel 13415:     my %hostname;
1.844     albertel 13416:     my %hostdom;
1.845     albertel 13417:     my %libserv;
1.852     albertel 13418:     my $loaded;
1.888     albertel 13419:     my %name_to_host;
1.1074    raeburn  13420:     my %internetdom;
1.1107    raeburn  13421:     my %LC_dns_serv;
1.852     albertel 13422: 
                   13423:     sub parse_hosts_tab {
                   13424: 	my ($file) = @_;
                   13425: 	foreach my $configline (@$file) {
                   13426: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13427:             chomp($configline);
                   13428: 	    if ($configline =~ /^\^/) {
                   13429:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13430:                     $LC_dns_serv{$1} = 1;
                   13431:                 }
                   13432:                 next;
                   13433:             }
1.1074    raeburn  13434: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13435: 	    $name=~s/\s//g;
                   13436: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13437:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13438:                     my $curr = $hostname{$id};
                   13439:                     my $skip;
                   13440:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13441:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13442:                             $skip = 1;
                   13443:                         } else {
                   13444:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13445:                         }
                   13446:                     }
                   13447:                     unless ($skip) {
                   13448:                         push(@{$name_to_host{$name}},$id);
                   13449:                     }
                   13450:                 } else {
                   13451:                     push(@{$name_to_host{$name}},$id);
                   13452:                 }
1.852     albertel 13453: 		$hostname{$id}=$name;
                   13454: 		$hostdom{$id}=$domain;
                   13455: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13456:                 if (defined($protocol)) {
                   13457:                     if ($protocol eq 'https') {
                   13458:                         $protocol{$id} = $protocol;
                   13459:                     } else {
                   13460:                         $protocol{$id} = 'http'; 
                   13461:                     }
1.968     raeburn  13462:                 } else {
1.969     raeburn  13463:                     $protocol{$id} = 'http';
1.968     raeburn  13464:                 }
1.1074    raeburn  13465:                 if (defined($intdom)) {
                   13466:                     $internetdom{$id} = $intdom;
                   13467:                 }
1.852     albertel 13468: 	    }
                   13469: 	}
                   13470:     }
1.864     albertel 13471:     
                   13472:     sub reset_hosts_info {
1.897     albertel 13473: 	&purge_remembered();
1.864     albertel 13474: 	&reset_domain_info();
                   13475: 	&reset_hosts_ip_info();
1.892     albertel 13476: 	undef(%name_to_host);
1.864     albertel 13477: 	undef(%hostname);
                   13478: 	undef(%hostdom);
                   13479: 	undef(%libserv);
                   13480: 	undef($loaded);
                   13481:     }
1.1       albertel 13482: 
1.852     albertel 13483:     sub load_hosts_tab {
1.1172.2.70  raeburn  13484: 	my ($ignore_cache,$nocache) = @_;
                   13485: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13486: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13487: 	my @config = <$config>;
                   13488: 	&parse_hosts_tab(\@config);
                   13489: 	close($config);
                   13490: 	$loaded=1;
1.1       albertel 13491:     }
1.852     albertel 13492: 
1.838     albertel 13493:     sub hostname {
1.852     albertel 13494: 	&load_hosts_tab() if (!$loaded);
                   13495: 
1.838     albertel 13496: 	my ($lonid) = @_;
                   13497: 	return $hostname{$lonid};
                   13498:     }
1.845     albertel 13499: 
1.838     albertel 13500:     sub all_hostnames {
1.852     albertel 13501: 	&load_hosts_tab() if (!$loaded);
                   13502: 
1.838     albertel 13503: 	return %hostname;
                   13504:     }
1.845     albertel 13505: 
1.888     albertel 13506:     sub all_names {
1.1172.2.70  raeburn  13507:         my ($ignore_cache,$nocache) = @_;
                   13508: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13509: 
                   13510: 	return %name_to_host;
                   13511:     }
                   13512: 
1.974     raeburn  13513:     sub all_host_domain {
                   13514:         &load_hosts_tab() if (!$loaded);
                   13515:         return %hostdom;
                   13516:     }
                   13517: 
1.845     albertel 13518:     sub is_library {
1.852     albertel 13519: 	&load_hosts_tab() if (!$loaded);
                   13520: 
1.845     albertel 13521: 	return exists($libserv{$_[0]});
                   13522:     }
                   13523: 
                   13524:     sub all_library {
1.852     albertel 13525: 	&load_hosts_tab() if (!$loaded);
                   13526: 
1.845     albertel 13527: 	return %libserv;
                   13528:     }
                   13529: 
1.1062    droeschl 13530:     sub unique_library {
                   13531: 	#2x reverse removes all hostnames that appear more than once
                   13532:         my %unique = reverse &all_library();
                   13533:         return reverse %unique;
                   13534:     }
                   13535: 
1.841     albertel 13536:     sub get_servers {
1.852     albertel 13537: 	&load_hosts_tab() if (!$loaded);
                   13538: 
1.841     albertel 13539: 	my ($domain,$type) = @_;
                   13540: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13541: 	                                          : %hostname;
                   13542: 	my %result;
1.842     albertel 13543: 	if (ref($domain) eq 'ARRAY') {
                   13544: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13545: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13546: 		    $result{$host} = $hostname;
                   13547: 		}
                   13548: 	    }
                   13549: 	} else {
                   13550: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13551: 		if ($hostdom{$host} eq $domain) {
                   13552: 		    $result{$host} = $hostname;
                   13553: 		}
1.841     albertel 13554: 	    }
                   13555: 	}
                   13556: 	return %result;
                   13557:     }
1.845     albertel 13558: 
1.1062    droeschl 13559:     sub get_unique_servers {
                   13560:         my %unique = reverse &get_servers(@_);
                   13561: 	return reverse %unique;
                   13562:     }
                   13563: 
1.844     albertel 13564:     sub host_domain {
1.852     albertel 13565: 	&load_hosts_tab() if (!$loaded);
                   13566: 
1.844     albertel 13567: 	my ($lonid) = @_;
                   13568: 	return $hostdom{$lonid};
                   13569:     }
                   13570: 
1.841     albertel 13571:     sub all_domains {
1.852     albertel 13572: 	&load_hosts_tab() if (!$loaded);
                   13573: 
1.841     albertel 13574: 	my %seen;
                   13575: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13576: 	return @uniq;
                   13577:     }
1.1074    raeburn  13578: 
                   13579:     sub internet_dom {
                   13580:         &load_hosts_tab() if (!$loaded);
                   13581: 
                   13582:         my ($lonid) = @_;
                   13583:         return $internetdom{$lonid};
                   13584:     }
1.1107    raeburn  13585: 
                   13586:     sub is_LC_dns {
                   13587:         &load_hosts_tab() if (!$loaded);
                   13588: 
                   13589:         my ($hostname) = @_;
                   13590:         return exists($LC_dns_serv{$hostname});
                   13591:     }
                   13592: 
1.1       albertel 13593: }
                   13594: 
1.847     albertel 13595: { 
                   13596:     my %iphost;
1.856     albertel 13597:     my %name_to_ip;
                   13598:     my %lonid_to_ip;
1.869     albertel 13599: 
1.847     albertel 13600:     sub get_hosts_from_ip {
                   13601: 	my ($ip) = @_;
                   13602: 	my %iphosts = &get_iphost();
                   13603: 	if (ref($iphosts{$ip})) {
                   13604: 	    return @{$iphosts{$ip}};
                   13605: 	}
                   13606: 	return;
1.839     albertel 13607:     }
1.864     albertel 13608:     
                   13609:     sub reset_hosts_ip_info {
                   13610: 	undef(%iphost);
                   13611: 	undef(%name_to_ip);
                   13612: 	undef(%lonid_to_ip);
                   13613:     }
1.856     albertel 13614: 
                   13615:     sub get_host_ip {
                   13616: 	my ($lonid) = @_;
                   13617: 	if (exists($lonid_to_ip{$lonid})) {
                   13618: 	    return $lonid_to_ip{$lonid};
                   13619: 	}
                   13620: 	my $name=&hostname($lonid);
                   13621:    	my $ip = gethostbyname($name);
                   13622: 	return if (!$ip || length($ip) ne 4);
                   13623: 	$ip=inet_ntoa($ip);
                   13624: 	$name_to_ip{$name}   = $ip;
                   13625: 	$lonid_to_ip{$lonid} = $ip;
                   13626: 	return $ip;
                   13627:     }
1.847     albertel 13628:     
                   13629:     sub get_iphost {
1.1172.2.70  raeburn  13630: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13631: 
1.869     albertel 13632: 	if (!$ignore_cache) {
                   13633: 	    if (%iphost) {
                   13634: 		return %iphost;
                   13635: 	    }
                   13636: 	    my ($ip_info,$cached)=
                   13637: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13638: 	    if ($cached) {
                   13639: 		%iphost      = %{$ip_info->[0]};
                   13640: 		%name_to_ip  = %{$ip_info->[1]};
                   13641: 		%lonid_to_ip = %{$ip_info->[2]};
                   13642: 		return %iphost;
                   13643: 	    }
                   13644: 	}
1.894     albertel 13645: 
                   13646: 	# get yesterday's info for fallback
                   13647: 	my %old_name_to_ip;
                   13648: 	my ($ip_info,$cached)=
                   13649: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13650: 	if ($cached) {
                   13651: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13652: 	}
                   13653: 
1.1172.2.70  raeburn  13654: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13655: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13656: 	    my $ip;
                   13657: 	    if (!exists($name_to_ip{$name})) {
                   13658: 		$ip = gethostbyname($name);
                   13659: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13660: 		    if (defined($old_name_to_ip{$name})) {
                   13661: 			$ip = $old_name_to_ip{$name};
                   13662: 			&logthis("Can't find $name defaulting to old $ip");
                   13663: 		    } else {
                   13664: 			&logthis("Name $name no IP found");
                   13665: 			next;
                   13666: 		    }
                   13667: 		} else {
                   13668: 		    $ip=inet_ntoa($ip);
1.847     albertel 13669: 		}
                   13670: 		$name_to_ip{$name} = $ip;
                   13671: 	    } else {
                   13672: 		$ip = $name_to_ip{$name};
1.653     albertel 13673: 	    }
1.888     albertel 13674: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13675: 		$lonid_to_ip{$id} = $ip;
                   13676: 	    }
                   13677: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13678: 	}
1.1172.2.70  raeburn  13679:         unless ($nocache) {
                   13680: 	    &do_cache_new('iphost','iphost',
                   13681: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13682: 		          48*60*60);
                   13683:         }
1.869     albertel 13684: 
1.847     albertel 13685: 	return %iphost;
1.598     albertel 13686:     }
                   13687: 
1.992     raeburn  13688:     #
                   13689:     #  Given a DNS returns the loncapa host name for that DNS 
                   13690:     # 
                   13691:     sub host_from_dns {
                   13692:         my ($dns) = @_;
                   13693:         my @hosts;
                   13694:         my $ip;
                   13695: 
1.993     raeburn  13696:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13697:             $ip = $name_to_ip{$dns};
                   13698:         }
                   13699:         if (!$ip) {
                   13700:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13701:             if (length($ip) == 4) { 
                   13702: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13703:             }
                   13704:         }
                   13705:         if ($ip) {
                   13706: 	    @hosts = get_hosts_from_ip($ip);
                   13707: 	    return $hosts[0];
                   13708:         }
                   13709:         return undef;
1.986     foxr     13710:     }
1.992     raeburn  13711: 
1.1074    raeburn  13712:     sub get_internet_names {
                   13713:         my ($lonid) = @_;
                   13714:         return if ($lonid eq '');
                   13715:         my ($idnref,$cached)=
                   13716:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13717:         if ($cached) {
                   13718:             return $idnref;
                   13719:         }
                   13720:         my $ip = &get_host_ip($lonid);
                   13721:         my @hosts = &get_hosts_from_ip($ip);
                   13722:         my %iphost = &get_iphost();
                   13723:         my (@idns,%seen);
                   13724:         foreach my $id (@hosts) {
                   13725:             my $dom = &host_domain($id);
                   13726:             my $prim_id = &domain($dom,'primary');
                   13727:             my $prim_ip = &get_host_ip($prim_id);
                   13728:             next if ($seen{$prim_ip});
                   13729:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13730:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13731:                     my $intdom = &internet_dom($id);
                   13732:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13733:                         push(@idns,$intdom);
                   13734:                     }
                   13735:                 }
                   13736:             }
                   13737:             $seen{$prim_ip} = 1;
                   13738:         }
1.1172.2.23  raeburn  13739:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13740:     }
                   13741: 
1.986     foxr     13742: }
                   13743: 
1.1079    raeburn  13744: sub all_loncaparevs {
1.1172.2.39  raeburn  13745:     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  13746: }
                   13747: 
1.1172.2.27  raeburn  13748: # ------------------------------------------------------- Read loncaparev table
                   13749: {
                   13750:     sub load_loncaparevs {
                   13751:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  13752:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  13753:                 while (my $configline=<$config>) {
                   13754:                     chomp($configline);
                   13755:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13756:                     $loncaparevs{$hostid}=$loncaparev;
                   13757:                 }
                   13758:                 close($config);
                   13759:             }
                   13760:         }
                   13761:     }
                   13762: }
                   13763: 
                   13764: # ----------------------------------------------------- Read serverhostID table
                   13765: {
                   13766:     sub load_serverhomeIDs {
                   13767:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  13768:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  13769:                 while (my $configline=<$config>) {
                   13770:                     chomp($configline);
                   13771:                     my ($name,$id)=split(/:/,$configline);
                   13772:                     $serverhomeIDs{$name}=$id;
                   13773:                 }
                   13774:                 close($config);
                   13775:             }
                   13776:         }
                   13777:     }
                   13778: }
                   13779: 
                   13780: 
1.862     albertel 13781: BEGIN {
                   13782: 
                   13783: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13784:     unless ($readit) {
                   13785: {
                   13786:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13787:     %perlvar = (%perlvar,%{$configvars});
                   13788: }
                   13789: 
                   13790: 
1.1       albertel 13791: # ------------------------------------------------------ Read spare server file
                   13792: {
1.1172.2.96  raeburn  13793:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13794: 
                   13795:     while (my $configline=<$config>) {
                   13796:        chomp($configline);
1.284     matthew  13797:        if ($configline) {
1.784     albertel 13798: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13799: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13800: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13801:        }
                   13802:     }
1.448     albertel 13803:     close($config);
1.1       albertel 13804: }
1.11      www      13805: # ------------------------------------------------------------ Read permissions
                   13806: {
1.1172.2.96  raeburn  13807:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13808: 
                   13809:     while (my $configline=<$config>) {
1.448     albertel 13810: 	chomp($configline);
                   13811: 	if ($configline) {
                   13812: 	    my ($role,$perm)=split(/ /,$configline);
                   13813: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13814: 	}
1.11      www      13815:     }
1.448     albertel 13816:     close($config);
1.11      www      13817: }
                   13818: 
                   13819: # -------------------------------------------- Read plain texts for permissions
                   13820: {
1.1172.2.96  raeburn  13821:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13822: 
                   13823:     while (my $configline=<$config>) {
1.448     albertel 13824: 	chomp($configline);
                   13825: 	if ($configline) {
1.742     raeburn  13826: 	    my ($short,@plain)=split(/:/,$configline);
                   13827:             %{$prp{$short}} = ();
                   13828: 	    if (@plain > 0) {
                   13829:                 $prp{$short}{'std'} = $plain[0];
                   13830:                 for (my $i=1; $i<@plain; $i++) {
                   13831:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13832:                 }
                   13833:             }
1.448     albertel 13834: 	}
1.135     www      13835:     }
1.448     albertel 13836:     close($config);
1.135     www      13837: }
                   13838: 
                   13839: # ---------------------------------------------------------- Read package table
                   13840: {
1.1172.2.96  raeburn  13841:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13842: 
                   13843:     while (my $configline=<$config>) {
1.483     albertel 13844: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13845: 	chomp($configline);
                   13846: 	my ($short,$plain)=split(/:/,$configline);
                   13847: 	my ($pack,$name)=split(/\&/,$short);
                   13848: 	if ($plain ne '') {
                   13849: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13850: 	    $packagetab{$short}=$plain; 
                   13851: 	}
1.11      www      13852:     }
1.448     albertel 13853:     close($config);
1.329     matthew  13854: }
                   13855: 
1.1172.2.27  raeburn  13856: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  13857: 
1.1172.2.27  raeburn  13858: &load_loncaparevs();
                   13859: 
                   13860: # ------------------------------------------------------- Read serverhostID table
                   13861: 
                   13862: &load_serverhomeIDs();
1.1074    raeburn  13863: 
1.1172.2.27  raeburn  13864: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13865: {
                   13866:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13867:     if (-e $file) {
                   13868:         my $parser = HTML::LCParser->new($file);
                   13869:         while (my $token = $parser->get_token()) {
                   13870:             if ($token->[0] eq 'S') {
                   13871:                 my $item = $token->[1];
                   13872:                 my $name = $token->[2]{'name'};
                   13873:                 my $value = $token->[2]{'value'};
                   13874:                 if ($item ne '' && $name ne '' && $value ne '') {
                   13875:                     my $release = $parser->get_text();
                   13876:                     $release =~ s/(^\s*|\s*$ )//gx;
                   13877:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   13878:                 }
                   13879:             }
                   13880:         }
                   13881:     }
1.1073    raeburn  13882: }
                   13883: 
1.1138    raeburn  13884: # ---------------------------------------------------------- Read managers table
                   13885: {
                   13886:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  13887:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  13888:             while (my $configline=<$config>) {
                   13889:                 chomp($configline);
                   13890:                 next if ($configline =~ /^\#/);
                   13891:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13892:                     $managerstab{$configline} = 1;
                   13893:                 }
                   13894:             }
                   13895:             close($config);
                   13896:         }
                   13897:     }
                   13898: }
                   13899: 
1.329     matthew  13900: # ------------- set up temporary directory
                   13901: {
1.1117    foxr     13902:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13903: 
1.11      www      13904: }
                   13905: 
1.1172.2.104  raeburn  13906: # ------------- set default texengine (domain default overrides this)
                   13907: {
                   13908:     $deftex = LONCAPA::texengine();
                   13909: }
                   13910: 
1.794     albertel 13911: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13912: 				'compress_threshold'=> 20_000,
                   13913:  			        });
1.185     www      13914: 
1.281     www      13915: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13916: $dumpcount=0;
1.958     www      13917: $locknum=0;
1.22      www      13918: 
1.163     harris41 13919: &logtouch();
1.672     albertel 13920: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13921: $readit=1;
1.564     albertel 13922:     {
                   13923: 	use integer;
                   13924: 	my $test=(2**32)+1;
1.568     albertel 13925: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13926: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13927:     }
1.195     www      13928: }
1.1       albertel 13929: }
1.179     www      13930: 
1.1       albertel 13931: 1;
1.191     harris41 13932: __END__
                   13933: 
1.243     albertel 13934: =pod
                   13935: 
1.191     harris41 13936: =head1 NAME
                   13937: 
1.243     albertel 13938: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13939: 
                   13940: =head1 SYNOPSIS
                   13941: 
1.243     albertel 13942: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13943: 
                   13944:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13945: 
1.243     albertel 13946: Common parameters:
                   13947: 
                   13948: =over 4
                   13949: 
                   13950: =item *
                   13951: 
                   13952: $uname : an internal username (if $cname expecting a course Id specifically)
                   13953: 
                   13954: =item *
                   13955: 
                   13956: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13957: 
                   13958: =item *
                   13959: 
                   13960: $symb : a resource instance identifier
                   13961: 
                   13962: =item *
                   13963: 
                   13964: $namespace : the name of a .db file that contains the data needed or
                   13965: being set.
                   13966: 
                   13967: =back
                   13968: 
1.394     bowersj2 13969: =head1 OVERVIEW
1.191     harris41 13970: 
1.394     bowersj2 13971: lonnet provides subroutines which interact with the
                   13972: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13973: about classes, users, and resources.
1.243     albertel 13974: 
                   13975: For many of these objects you can also use this to store data about
                   13976: them or modify them in various ways.
1.191     harris41 13977: 
1.394     bowersj2 13978: =head2 Symbs
1.191     harris41 13979: 
1.394     bowersj2 13980: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13981: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13982: map, the resource number of the resource in the map, and the URL of
                   13983: the resource itself. The latter is somewhat redundant, but might help
                   13984: if maps change.
                   13985: 
                   13986: An example is
                   13987: 
                   13988:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13989: 
                   13990: The respective map entry is
                   13991: 
                   13992:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13993:   title="Problem 2">
                   13994:  </resource>
                   13995: 
                   13996: Symbs are used by the random number generator, as well as to store and
                   13997: restore data specific to a certain instance of for example a problem.
                   13998: 
                   13999: =head2 Storing And Retrieving Data
                   14000: 
                   14001: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14002: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14003: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14004: is is the non-critical message twin of cstore. These functions are for
                   14005: handlers to store a perl hash to a user's permanent data space in an
                   14006: easy manner, and to retrieve it again on another call. It is expected
                   14007: that a handler would use this once at the beginning to retrieve data,
                   14008: and then again once at the end to send only the new data back.
                   14009: 
                   14010: The data is stored in the user's data directory on the user's
                   14011: homeserver under the ID of the course.
                   14012: 
                   14013: The hash that is returned by restore will have all of the previous
                   14014: value for all of the elements of the hash.
                   14015: 
                   14016: Example:
                   14017: 
                   14018:  #creating a hash
                   14019:  my %hash;
                   14020:  $hash{'foo'}='bar';
                   14021: 
                   14022:  #storing it
                   14023:  &Apache::lonnet::cstore(\%hash);
                   14024: 
                   14025:  #changing a value
                   14026:  $hash{'foo'}='notbar';
                   14027: 
                   14028:  #adding a new value
                   14029:  $hash{'bar'}='foo';
                   14030:  &Apache::lonnet::cstore(\%hash);
                   14031: 
                   14032:  #retrieving the hash
                   14033:  my %history=&Apache::lonnet::restore();
                   14034: 
                   14035:  #print the hash
                   14036:  foreach my $key (sort(keys(%history))) {
                   14037:    print("\%history{$key} = $history{$key}");
                   14038:  }
                   14039: 
                   14040: Will print out:
1.191     harris41 14041: 
1.394     bowersj2 14042:  %history{1:foo} = bar
                   14043:  %history{1:keys} = foo:timestamp
                   14044:  %history{1:timestamp} = 990455579
                   14045:  %history{2:bar} = foo
                   14046:  %history{2:foo} = notbar
                   14047:  %history{2:keys} = foo:bar:timestamp
                   14048:  %history{2:timestamp} = 990455580
                   14049:  %history{bar} = foo
                   14050:  %history{foo} = notbar
                   14051:  %history{timestamp} = 990455580
                   14052:  %history{version} = 2
                   14053: 
                   14054: Note that the special hash entries C<keys>, C<version> and
                   14055: C<timestamp> were added to the hash. C<version> will be equal to the
                   14056: total number of versions of the data that have been stored. The
                   14057: C<timestamp> attribute will be the UNIX time the hash was
                   14058: stored. C<keys> is available in every historical section to list which
                   14059: keys were added or changed at a specific historical revision of a
                   14060: hash.
                   14061: 
                   14062: B<Warning>: do not store the hash that restore returns directly. This
                   14063: will cause a mess since it will restore the historical keys as if the
                   14064: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14065: 
1.394     bowersj2 14066: Calling convention:
1.191     harris41 14067: 
1.1172.2.27  raeburn  14068:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14069:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14070: 
1.394     bowersj2 14071: For more detailed information, see lonnet specific documentation.
1.191     harris41 14072: 
1.394     bowersj2 14073: =head1 RETURN MESSAGES
1.191     harris41 14074: 
1.394     bowersj2 14075: =over 4
1.191     harris41 14076: 
1.394     bowersj2 14077: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14078: 
1.394     bowersj2 14079: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14080: when the connection is brought back up
1.191     harris41 14081: 
1.394     bowersj2 14082: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14083: for later delivery
1.191     harris41 14084: 
1.967     bisitz   14085: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14086: 
1.394     bowersj2 14087: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14088: that was requested
1.191     harris41 14089: 
1.243     albertel 14090: =back
1.191     harris41 14091: 
1.243     albertel 14092: =head1 PUBLIC SUBROUTINES
1.191     harris41 14093: 
1.243     albertel 14094: =head2 Session Environment Functions
1.191     harris41 14095: 
1.243     albertel 14096: =over 4
1.191     harris41 14097: 
1.394     bowersj2 14098: =item * 
                   14099: X<appenv()>
1.949     raeburn  14100: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14101: the user envirnoment file, and will be restored for each access this
1.620     albertel 14102: user makes during this session, also modifies the %env for the current
1.949     raeburn  14103: process. Optional rolesarrayref - if defined contains a reference to an array
                   14104: of roles which are exempt from the restriction on modifying user.role entries 
                   14105: in the user's environment.db and in %env.    
1.191     harris41 14106: 
                   14107: =item *
1.394     bowersj2 14108: X<delenv()>
1.987     raeburn  14109: B<delenv($delthis,$regexp)>: removes all items from the session
                   14110: environment file that begin with $delthis. If the 
                   14111: optional second arg - $regexp - is true, $delthis is treated as a 
                   14112: regular expression, otherwise \Q$delthis\E is used. 
                   14113: The values are also deleted from the current processes %env.
1.191     harris41 14114: 
1.795     albertel 14115: =item * get_env_multiple($name) 
                   14116: 
                   14117: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14118: values may be defined and end up as an array ref.
                   14119: 
                   14120: returns an array of values
                   14121: 
1.243     albertel 14122: =back
                   14123: 
                   14124: =head2 User Information
1.191     harris41 14125: 
1.243     albertel 14126: =over 4
1.191     harris41 14127: 
                   14128: =item *
1.394     bowersj2 14129: X<queryauthenticate()>
                   14130: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14131: authentication scheme
                   14132: 
                   14133: =item *
1.394     bowersj2 14134: X<authenticate()>
1.1073    raeburn  14135: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14136: authenticate user from domain's lib servers (first use the current
                   14137: one). C<$upass> should be the users password.
1.1073    raeburn  14138: $checkdefauth is optional (value is 1 if a check should be made to
                   14139:    authenticate user using default authentication method, and allow
                   14140:    account creation if username does not have account in the domain).
                   14141: $clientcancheckhost is optional (value is 1 if checking whether the
                   14142:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14143: 
                   14144: =item *
1.394     bowersj2 14145: X<homeserver()>
                   14146: B<homeserver($uname,$udom)>: find the server which has
                   14147: the user's directory and files (there must be only one), this caches
                   14148: the answer, and also caches if there is a borken connection.
1.191     harris41 14149: 
                   14150: =item *
1.394     bowersj2 14151: X<idget()>
                   14152: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14153: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14154: username, and only 1 username per ID in a specific domain) (returns
                   14155: hash: id=>name,id=>name)
1.191     harris41 14156: 
                   14157: =item *
1.394     bowersj2 14158: X<idrget()>
                   14159: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14160: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14161: 
                   14162: =item *
1.394     bowersj2 14163: X<idput()>
                   14164: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14165: 
                   14166: =item *
1.394     bowersj2 14167: X<rolesinit()>
1.1169    droeschl 14168: B<rolesinit($udom,$username)>: get user privileges.
                   14169: returns user role, first access and timer interval hashes
1.243     albertel 14170: 
                   14171: =item *
1.1171    droeschl 14172: X<privileged()>
                   14173: B<privileged($username,$domain)>: returns a true if user has a
                   14174: privileged and active role (i.e. su or dc), false otherwise.
                   14175: 
                   14176: =item *
1.551     albertel 14177: X<getsection()>
                   14178: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14179: course $cname, return section name/number or '' for "not in course"
                   14180: and '-1' for "no section"
                   14181: 
                   14182: =item *
1.394     bowersj2 14183: X<userenvironment()>
                   14184: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14185: passed in @what from the requested user's environment, returns a hash
                   14186: 
1.858     raeburn  14187: =item * 
                   14188: X<userlog_query()>
1.859     albertel 14189: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14190: activity.log file. %filters defines filters applied when parsing the
                   14191: log file. These can be start or end timestamps, or the type of action
                   14192: - log to look for Login or Logout events, check for Checkin or
                   14193: Checkout, role for role selection. The response is in the form
                   14194: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14195: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14196: 
1.243     albertel 14197: =back
                   14198: 
                   14199: =head2 User Roles
                   14200: 
                   14201: =over 4
                   14202: 
                   14203: =item *
                   14204: 
1.1172.2.65  raeburn  14205: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14206: returns codes for allowed actions.
                   14207: 
                   14208: The first argument is required, all others are optional.
                   14209: 
                   14210: $priv is the privilege being checked.
                   14211: $uri contains additional information about what is being checked for access (e.g.,
                   14212: URL, course ID etc.).
                   14213: $symb is the unique resource instance identifier in a course; if needed,
                   14214: but not provided, it will be retrieved via a call to &symbread().
                   14215: $role is the role for which a priv is being checked (only used if priv is evb).
                   14216: $clientip is the user's IP address (only used when checking for access to portfolio
                   14217: files).
                   14218: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14219: prevents recursive calls to &allowed.
                   14220: 
1.243     albertel 14221:  F: full access
                   14222:  U,I,K: authentication modes (cxx only)
                   14223:  '': forbidden
                   14224:  1: user needs to choose course
                   14225:  2: browse allowed
1.766     albertel 14226:  A: passphrase authentication needed
1.1172.2.65  raeburn  14227:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14228: 
                   14229: =item *
                   14230: 
1.1172.2.13  raeburn  14231: constructaccess($url,$setpriv) : check for access to construction space URL
                   14232: 
                   14233: See if the owner domain and name in the URL match those in the
                   14234: expected environment.  If so, return three element list
                   14235: ($ownername,$ownerdomain,$ownerhome).
                   14236: 
                   14237: Otherwise return the null string.
                   14238: 
                   14239: If second argument 'setpriv' is true, it assigns the privileges,
                   14240: and returns the same three element list, unless the owner has
                   14241: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14242: in which case the null string is returned.
                   14243: 
                   14244: =item *
                   14245: 
1.1172.2.84  raeburn  14246: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14247: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14248: for system, domain, and course level. $uname and $udom are optional (current
                   14249: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14250: 
                   14251: =item *
                   14252: 
1.988     raeburn  14253: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14254: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14255: $type is Course (default) or Community.
1.988     raeburn  14256: If $forcedefault evaluates to true, text returned will be default 
                   14257: text for $type. Otherwise, if this is a course, the text returned 
                   14258: will be a custom name for the role (if defined in the course's 
                   14259: environment).  If no custom name is defined the default is returned.
                   14260:    
1.832     raeburn  14261: =item *
                   14262: 
1.1172.2.23  raeburn  14263: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14264: All arguments are optional. Returns a hash of a roles, either for
                   14265: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14266: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14267: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14268: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14269: For each key, value is set to colon-separated start and end times for
                   14270: the role.  If no username and domain are specified, will default to
1.934     raeburn  14271: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14272: of role statuses (active, future or previous), roles 
                   14273: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14274: to restrict the list of roles reported. If no array ref is 
                   14275: provided for types, will default to return only active roles.
1.834     albertel 14276: 
1.1172.2.13  raeburn  14277: =item *
                   14278: 
                   14279: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14280: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14281: 
                   14282: Additional optional arguments are: $type (if role checking is to be restricted
                   14283: to certain user status types -- previous (expired roles), active (currently
                   14284: available roles) or future (roles available in the future), and
                   14285: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14286: have active Domain Coordinator role in course's domain or in additional
                   14287: domains (specified in 'Domains to check for privileged users' in course
                   14288: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14289: 
                   14290: =item *
                   14291: 
                   14292: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14293: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14294: $possdomains and $possroles are optional array refs -- to domains to check and
                   14295: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14296: users' roles.db to check for a dc or su role in any domain. This can be
                   14297: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14298: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14299: this then allows &privileged_by_domain() to be used, which caches the identity
                   14300: of privileged users, eliminating the need for repeated calls to &dump().
                   14301: 
                   14302: =item *
                   14303: 
                   14304: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14305: where the outer hash keys are domains specified in the $possdomains array ref,
                   14306: next inner hash keys are privileged roles specified in the $roles array ref,
                   14307: and the innermost hash contains key = value pairs for username:domain = end:start
                   14308: for active or future "privileged" users with that role in that domain. To avoid
                   14309: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14310: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14311: 
1.243     albertel 14312: =back
                   14313: 
                   14314: =head2 User Modification
                   14315: 
                   14316: =over 4
                   14317: 
                   14318: =item *
                   14319: 
1.957     raeburn  14320: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14321: user for the level given by URL.  Optional start and end dates (leave empty
                   14322: string or zero for "no date")
1.191     harris41 14323: 
                   14324: =item *
                   14325: 
1.243     albertel 14326: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14327: change a users, password, possible return values are: ok,
                   14328: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14329: refused
1.191     harris41 14330: 
                   14331: =item *
                   14332: 
1.243     albertel 14333: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14334: 
                   14335: =item *
                   14336: 
1.1058    raeburn  14337: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14338:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14339: 
                   14340: will update user information (firstname,middlename,lastname,generation,
                   14341: permanentemail), and if forceid is true, student/employee ID also.
                   14342: A user's institutional affiliation(s) can also be updated.
                   14343: User information fields will not be overwritten with empty entries 
                   14344: unless the field is included in the $candelete array reference.
                   14345: This array is included when a single user is modified via "Manage Users",
                   14346: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14347: 
                   14348: =item *
                   14349: 
1.286     matthew  14350: modifystudent
                   14351: 
1.957     raeburn  14352: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14353: The course id is resolved based on the current user's environment.  
                   14354: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14355: associated with a course.
                   14356: 
1.297     matthew  14357: This call is essentially a wrapper for lonnet::modifyuser and
                   14358: lonnet::modify_student_enrollment
1.286     matthew  14359: 
                   14360: Inputs: 
                   14361: 
                   14362: =over 4
                   14363: 
1.957     raeburn  14364: =item B<$udom> Student's loncapa domain
1.286     matthew  14365: 
1.957     raeburn  14366: =item B<$uname> Student's loncapa login name
1.286     matthew  14367: 
1.964     bisitz   14368: =item B<$uid> Student/Employee ID
1.286     matthew  14369: 
1.957     raeburn  14370: =item B<$umode> Student's authentication mode
1.286     matthew  14371: 
1.957     raeburn  14372: =item B<$upass> Student's password
1.286     matthew  14373: 
1.957     raeburn  14374: =item B<$first> Student's first name
1.286     matthew  14375: 
1.957     raeburn  14376: =item B<$middle> Student's middle name
1.286     matthew  14377: 
1.957     raeburn  14378: =item B<$last> Student's last name
1.286     matthew  14379: 
1.957     raeburn  14380: =item B<$gene> Student's generation
1.286     matthew  14381: 
1.957     raeburn  14382: =item B<$usec> Student's section in course
1.286     matthew  14383: 
                   14384: =item B<$end> Unix time of the roles expiration
                   14385: 
                   14386: =item B<$start> Unix time of the roles start date
                   14387: 
                   14388: =item B<$forceid> If defined, allow $uid to be changed
                   14389: 
                   14390: =item B<$desiredhome> server to use as home server for student
                   14391: 
1.957     raeburn  14392: =item B<$email> Student's permanent e-mail address
                   14393: 
                   14394: =item B<$type> Type of enrollment (auto or manual)
                   14395: 
1.963     raeburn  14396: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14397: 
                   14398: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14399: 
1.963     raeburn  14400: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14401: 
1.963     raeburn  14402: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14403: 
1.1172.2.19  raeburn  14404: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14405: 
                   14406: =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  14407: 
1.286     matthew  14408: =back
1.297     matthew  14409: 
                   14410: =item *
                   14411: 
                   14412: modify_student_enrollment
                   14413: 
1.1172.2.31  raeburn  14414: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14415: 'role.request.course' must be defined for this function to proceed.
                   14416: 
                   14417: Inputs:
                   14418: 
                   14419: =over 4
                   14420: 
1.1172.2.31  raeburn  14421: =item $udom, student's domain
1.297     matthew  14422: 
1.1172.2.31  raeburn  14423: =item $uname, student's name
1.297     matthew  14424: 
1.1172.2.31  raeburn  14425: =item $uid, student's user id
1.297     matthew  14426: 
1.1172.2.31  raeburn  14427: =item $first, student's first name
1.297     matthew  14428: 
                   14429: =item $middle
                   14430: 
                   14431: =item $last
                   14432: 
                   14433: =item $gene
                   14434: 
                   14435: =item $usec
                   14436: 
                   14437: =item $end
                   14438: 
                   14439: =item $start
                   14440: 
1.957     raeburn  14441: =item $type
                   14442: 
                   14443: =item $locktype
                   14444: 
                   14445: =item $cid
                   14446: 
                   14447: =item $selfenroll
                   14448: 
                   14449: =item $context
                   14450: 
1.1172.2.19  raeburn  14451: =item $credits, number of credits student will earn from this class
                   14452: 
1.1172.2.76  raeburn  14453: =item $instsec, institutional course section code for student
                   14454: 
1.297     matthew  14455: =back
                   14456: 
1.191     harris41 14457: 
                   14458: =item *
                   14459: 
1.243     albertel 14460: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14461: custom role; give a custom role to a user for the level given by URL.  Specify
                   14462: name and domain of role author, and role name
1.191     harris41 14463: 
                   14464: =item *
                   14465: 
1.243     albertel 14466: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14467: 
                   14468: =item *
                   14469: 
1.243     albertel 14470: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14471: 
                   14472: =back
                   14473: 
                   14474: =head2 Course Infomation
                   14475: 
                   14476: =over 4
1.191     harris41 14477: 
                   14478: =item *
                   14479: 
1.1118    foxr     14480: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14481: specified course id, including all environment settings for the
                   14482: course, the description of the course will be in the hash under the
                   14483: key 'description'
1.191     harris41 14484: 
1.1118    foxr     14485: $options is an optional parameter that if supplied is a hash reference that controls
                   14486: what how this function works.  It has the following key/values:
                   14487: 
                   14488: =over 4
                   14489: 
                   14490: =item freshen_cache
                   14491: 
                   14492: If defined, and the environment cache for the course is valid, it is 
                   14493: returned in the returned hash.
                   14494: 
                   14495: =item one_time
                   14496: 
                   14497: If defined, the last cache time is set to _now_
                   14498: 
                   14499: =item user
                   14500: 
                   14501: If defined, the supplied username is used instead of the current user.
                   14502: 
                   14503: 
                   14504: =back
                   14505: 
1.191     harris41 14506: =item *
                   14507: 
1.624     albertel 14508: resdata($name,$domain,$type,@which) : request for current parameter
                   14509: setting for a specific $type, where $type is either 'course' or 'user',
                   14510: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14511: answers for 10 minutes.
1.243     albertel 14512: 
1.877     foxr     14513: =item *
                   14514: 
                   14515: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14516: data base, returning a hash that is keyed by the resource name and has
                   14517: values that are the resource value.  I believe that the timestamps and
                   14518: versions are also returned.
                   14519: 
1.1172.2.31  raeburn  14520: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14521: supplemental content area. This routine caches the number of files for
                   14522: 10 minutes.
                   14523: 
1.243     albertel 14524: =back
                   14525: 
                   14526: =head2 Course Modification
                   14527: 
                   14528: =over 4
1.191     harris41 14529: 
                   14530: =item *
                   14531: 
1.243     albertel 14532: writecoursepref($courseid,%prefs) : write preferences (environment
                   14533: database) for a course
1.191     harris41 14534: 
                   14535: =item *
                   14536: 
1.1011    raeburn  14537: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14538: 
                   14539: =item *
                   14540: 
1.1038    raeburn  14541: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14542: 
1.1167    droeschl 14543: =item *
                   14544: 
                   14545: is_course($courseid), is_course($cdom, $cnum)
                   14546: 
                   14547: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14548: two component version $cdom, $cnum. It checks if the specified course exists.
                   14549: 
                   14550: Returns:
                   14551:     undef if the course doesn't exist, otherwise
                   14552:     in scalar context the combined courseid.
                   14553:     in list context the two components of the course identifier, domain and 
                   14554:     courseid.    
                   14555: 
1.243     albertel 14556: =back
                   14557: 
1.1172.2.109  raeburn  14558: =head2 Bubblesheet Configuration
                   14559: 
                   14560: =over 4
                   14561: 
                   14562: =item *
                   14563: 
                   14564: get_scantron_config($which)
                   14565: 
                   14566: $which - the name of the configuration to parse from the file.
                   14567: 
                   14568: Parses and returns the bubblesheet configuration line selected as a
                   14569: hash of configuration file fields.
                   14570: 
                   14571: 
                   14572: Returns:
                   14573:     If the named configuration is not in the file, an empty
                   14574:     hash is returned.
                   14575: 
                   14576:     a hash with the fields
                   14577:       name         - internal name for the this configuration setup
                   14578:       description  - text to display to operator that describes this config
                   14579:       CODElocation - if 0 or the string 'none'
                   14580:                           - no CODE exists for this config
                   14581:                      if -1 || the string 'letter'
                   14582:                           - a CODE exists for this config and is
                   14583:                             a string of letters
                   14584:                      Unsupported value (but planned for future support)
                   14585:                           if a positive integer
                   14586:                                - The CODE exists as the first n items from
                   14587:                                  the question section of the form
                   14588:                           if the string 'number'
                   14589:                                - The CODE exists for this config and is
                   14590:                                  a string of numbers
                   14591:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14592:                      the CODE starts
                   14593:       CODElength  - length of the CODE
                   14594:       IDstart     - column where the student/employee ID starts
                   14595:       IDlength    - length of the student/employee ID info
                   14596:       Qstart      - column where the information from the bubbled
                   14597:                     'questions' start
                   14598:       Qlength     - number of columns comprising a single bubble line from
                   14599:                     the sheet. (usually either 1 or 10)
                   14600:       Qon         - either a single character representing the character used
                   14601:                     to signal a bubble was chosen in the positional setup, or
                   14602:                     the string 'letter' if the letter of the chosen bubble is
                   14603:                     in the final, or 'number' if a number representing the
                   14604:                     chosen bubble is in the file (1->A 0->J)
                   14605:       Qoff        - the character used to represent that a bubble was
                   14606:                     left blank
                   14607:       PaperID     - if the scanning process generates a unique number for each
                   14608:                     sheet scanned the column that this ID number starts in
                   14609:       PaperIDlength - number of columns that comprise the unique ID number
                   14610:                       for the sheet of paper
                   14611:       FirstName   - column that the first name starts in
                   14612:       FirstNameLength - number of columns that the first name spans
                   14613:       LastName    - column that the last name starts in
                   14614:       LastNameLength - number of columns that the last name spans
                   14615:       BubblesPerRow - number of bubbles available in each row used to
                   14616:                       bubble an answer. (If not specified, 10 assumed).
                   14617: 
                   14618: 
                   14619: =item *
                   14620: 
                   14621: get_scantronformat_file($cdom)
                   14622: 
                   14623: $cdom - the course's domain (optional); if not supplied, uses
                   14624: domain for current $env{'request.course.id'}.
                   14625: 
                   14626: Returns an array containing lines from the scantron format file for
                   14627: the domain of the course.
                   14628: 
                   14629: If a url for a custom.tab file is listed in domain's configuration.db,
                   14630: lines are from this file.
                   14631: 
                   14632: Otherwise, if a default.tab has been published in RES space by the
                   14633: domainconfig user, lines are from this file.
                   14634: 
                   14635: Otherwise, fall back to getting lines from the legacy file on the
                   14636: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14637: 
                   14638: =back
                   14639: 
1.243     albertel 14640: =head2 Resource Subroutines
                   14641: 
                   14642: =over 4
1.191     harris41 14643: 
                   14644: =item *
                   14645: 
1.243     albertel 14646: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14647: 
                   14648: =item *
                   14649: 
1.243     albertel 14650: repcopy($filename) : subscribes to the requested file, and attempts to
                   14651: replicate from the owning library server, Might return
1.607     raeburn  14652: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14653: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14654: resource. Expects the local filesystem pathname
                   14655: (/home/httpd/html/res/....)
                   14656: 
                   14657: =back
                   14658: 
                   14659: =head2 Resource Information
                   14660: 
                   14661: =over 4
1.191     harris41 14662: 
                   14663: =item *
                   14664: 
1.1172.2.28  raeburn  14665: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14666: and returns the value of a variety of different possible values,
                   14667: $varname should be a request string, and the other parameters can be
                   14668: used to specify who and what one is asking about. Ordinarily, $cid 
                   14669: does not need to be specified, as it is retrived from 
                   14670: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14671: within lonuserstate::loadmap() when initializing a course, before
                   14672: $env{'request.course.id'} has been set, so it needs to be provided
                   14673: in that one case.
1.243     albertel 14674: 
                   14675: Possible values for $varname are environment.lastname (or other item
                   14676: from the envirnment hash), user.name (or someother aspect about the
                   14677: user), resource.0.maxtries (or some other part and parameter of a
                   14678: resource)
1.204     albertel 14679: 
                   14680: =item *
                   14681: 
1.243     albertel 14682: directcondval($number) : get current value of a condition; reads from a state
                   14683: string
1.204     albertel 14684: 
                   14685: =item *
                   14686: 
1.243     albertel 14687: condval($condidx) : value of condition index based on state
1.204     albertel 14688: 
                   14689: =item *
                   14690: 
1.243     albertel 14691: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14692: resource's metadata, $what should be either a specific key, or either
                   14693: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14694: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14695: 
                   14696: this function automatically caches all requests
1.191     harris41 14697: 
                   14698: =item *
                   14699: 
1.243     albertel 14700: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14701: network of library servers; returns file handle of where SQL and regex results
                   14702: will be stored for query
1.191     harris41 14703: 
                   14704: =item *
                   14705: 
1.1172.2.66  raeburn  14706: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14707: return symbolic list entry (all arguments optional).
                   14708: 
                   14709: Args: filename is the filename (including path) for the file for which a symb
                   14710: is required; donotrecurse, if true will prevent calls to allowed() being made
                   14711: to check access status if more than one resource was found in the bighash
                   14712: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   14713: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   14714: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14715: cause possible symbs to be checked to determine if they are subject to content
                   14716: blocking, if so they will not be included as possible symbs; possibles is a
                   14717: ref to a hash, which, as a side effect, will be populated with all possible
                   14718: symbs (content blocking not tested).
                   14719: 
1.243     albertel 14720: returns the data handle
1.191     harris41 14721: 
                   14722: =item *
                   14723: 
1.1172.2.17  raeburn  14724: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  14725: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14726: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  14727: on failure, user must be in a course, as it assumes the existence of
                   14728: the course initial hash, and uses $env('request.course.id'}.  The third
                   14729: arg is an optional reference to a scalar.  If this arg is passed in the
                   14730: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14731: encrypted; otherwise it will be null.
1.243     albertel 14732: 
1.191     harris41 14733: =item *
                   14734: 
1.243     albertel 14735: symbclean($symb) : removes versions numbers from a symb, returns the
                   14736: cleaned symb
1.191     harris41 14737: 
                   14738: =item *
                   14739: 
1.243     albertel 14740: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14741: course map, user must be in a course for it to work.
1.191     harris41 14742: 
                   14743: =item *
                   14744: 
1.243     albertel 14745: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14746: 
                   14747: =item *
                   14748: 
1.243     albertel 14749: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14750: a random seed, all arguments are optional, if they aren't sent it uses the
                   14751: environment to derive them. Note: if symb isn't sent and it can't get one
                   14752: from &symbread it will use the current time as its return value
1.191     harris41 14753: 
                   14754: =item *
                   14755: 
1.243     albertel 14756: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14757: unfakeable, receipt
1.191     harris41 14758: 
                   14759: =item *
                   14760: 
1.620     albertel 14761: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14762: 
                   14763: =item *
                   14764: 
1.243     albertel 14765: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14766: 
                   14767: =item *
                   14768: 
1.243     albertel 14769: 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 14770: 
                   14771: =item *
                   14772: 
1.243     albertel 14773: 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 14774: 
                   14775: =item *
                   14776: 
1.243     albertel 14777: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14778: 
                   14779: =item *
                   14780: 
1.243     albertel 14781: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14782: forcing spreadsheet to reevaluate the resource scores next time.
                   14783: 
1.1172.2.13  raeburn  14784: =item *
                   14785: 
                   14786: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14787: when viewing in course context.
                   14788: 
                   14789:  input: six args -- filename (decluttered), course number, course domain,
                   14790:                     url, symb (if registered) and group (if this is a
                   14791:                     group item -- e.g., bulletin board, group page etc.).
                   14792: 
                   14793:  output: array of five scalars --
                   14794:          $cfile -- url for file editing if editable on current server
                   14795:          $home -- homeserver of resource (i.e., for author if published,
                   14796:                                           or course if uploaded.).
                   14797:          $switchserver --  1 if server switch will be needed.
                   14798:          $forceedit -- 1 if icon/link should be to go to edit mode
                   14799:          $forceview -- 1 if icon/link should be to go to view mode
                   14800: 
                   14801: =item *
                   14802: 
                   14803: is_course_upload($file,$cnum,$cdom)
                   14804: 
                   14805: Used in course context to determine if current file was uploaded to
                   14806: the course (i.e., would be found in /userfiles/docs on the course's
                   14807: homeserver.
                   14808: 
                   14809:   input: 3 args -- filename (decluttered), course number and course domain.
                   14810:   output: boolean -- 1 if file was uploaded.
                   14811: 
1.243     albertel 14812: =back
                   14813: 
                   14814: =head2 Storing/Retreiving Data
                   14815: 
                   14816: =over 4
1.191     harris41 14817: 
                   14818: =item *
                   14819: 
1.1172.2.64  raeburn  14820: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   14821: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14822: the remaining args aren't required and if they aren't passed or are '' they will
                   14823: be derived from the env (with the exception of $laststore, which is an
                   14824: optional arg used when a user's submission is stored in grading).
                   14825: $laststore is $version=$timestamp, where $version is the most recent version
                   14826: number retrieved for the corresponding $symb in the $namespace db file, and
                   14827: $timestamp is the timestamp for that transaction (UNIX time).
                   14828: $laststore is currently only passed when cstore() is called by
                   14829: structuretags::finalize_storage().
1.191     harris41 14830: 
                   14831: =item *
                   14832: 
1.1172.2.64  raeburn  14833: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   14834: but uses critical subroutine
1.191     harris41 14835: 
                   14836: =item *
                   14837: 
1.243     albertel 14838: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14839: all args are optional
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.717     albertel 14843: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14844: dumps the complete (or key matching regexp) namespace into a hash
                   14845: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14846: normally &store()ed into
                   14847: 
                   14848: $range should be either an integer '100' (give me the first 100
                   14849:                                            matching records)
                   14850:               or be  two integers sperated by a - with no spaces
                   14851:                  '30-50' (give me the 30th through the 50th matching
                   14852:                           records)
                   14853: 
                   14854: 
                   14855: =item *
                   14856: 
1.1172.2.59  raeburn  14857: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14858: replaces a &store() version of data with a replacement set of data
                   14859: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  14860: reference. If $tolog is true, the transaction is logged in the courselog
                   14861: with an action=PUTSTORE.
1.717     albertel 14862: 
                   14863: =item *
                   14864: 
1.243     albertel 14865: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14866: works very similar to store/cstore, but all data is stored in a
                   14867: temporary location and can be reset using tmpreset, $storehash should
                   14868: be a hash reference, returns nothing on success
1.191     harris41 14869: 
                   14870: =item *
                   14871: 
1.243     albertel 14872: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14873: similar to restore, but all data is stored in a temporary location and
                   14874: can be reset using tmpreset. Returns a hash of values on success,
                   14875: error string otherwise.
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.243     albertel 14879: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14880: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14881: 
                   14882: =item *
                   14883: 
1.243     albertel 14884: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14885: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14886: 
                   14887: =item *
                   14888: 
1.243     albertel 14889: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14890: namesp ($udom and $uname are optional)
1.191     harris41 14891: 
                   14892: =item *
                   14893: 
1.702     albertel 14894: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14895: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14896: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14897: 
1.702     albertel 14898: $range should be either an integer '100' (give me the first 100
                   14899:                                            matching records)
                   14900:               or be  two integers sperated by a - with no spaces
                   14901:                  '30-50' (give me the 30th through the 50th matching
                   14902:                           records)
1.449     matthew  14903: =item *
                   14904: 
                   14905: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14906: $store can be a scalar, an array reference, or if the amount to be 
                   14907: incremented is > 1, a hash reference.
                   14908: 
                   14909: ($udom and $uname are optional)
1.191     harris41 14910: 
                   14911: =item *
                   14912: 
1.243     albertel 14913: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14914: ($udom and $uname are optional)
1.191     harris41 14915: 
                   14916: =item *
                   14917: 
1.243     albertel 14918: cput($namespace,$storehash,$udom,$uname) : critical put
                   14919: ($udom and $uname are optional)
1.191     harris41 14920: 
                   14921: =item *
                   14922: 
1.748     albertel 14923: newput($namespace,$storehash,$udom,$uname) :
                   14924: 
                   14925: Attempts to store the items in the $storehash, but only if they don't
                   14926: currently exist, if this succeeds you can be certain that you have 
                   14927: successfully created a new key value pair in the $namespace db.
                   14928: 
                   14929: 
                   14930: Args:
                   14931:  $namespace: name of database to store values to
                   14932:  $storehash: hashref to store to the db
                   14933:  $udom: (optional) domain of user containing the db
                   14934:  $uname: (optional) name of user caontaining the db
                   14935: 
                   14936: Returns:
                   14937:  'ok' -> succeeded in storing all keys of $storehash
                   14938:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14939:                         least <key> already existed in the db (other
                   14940:                         requested keys may also already exist)
1.967     bisitz   14941:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14942:  'con_lost' -> unable to contact request server
                   14943:  'refused' -> action was not allowed by remote machine
                   14944: 
                   14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14949: reference filled in from namesp (encrypts the return communication)
                   14950: ($udom and $uname are optional)
1.191     harris41 14951: 
                   14952: =item *
                   14953: 
1.243     albertel 14954: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14955: critical subroutine
                   14956: 
1.806     raeburn  14957: =item *
                   14958: 
1.860     raeburn  14959: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14960: array reference filled in from namespace found in domain level on either
                   14961: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14962: 
                   14963: =item *
                   14964: 
1.860     raeburn  14965: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14966: domain level either on specified domain server ($uhome) or primary domain 
                   14967: server ($udom and $uhome are optional)
1.806     raeburn  14968: 
1.943     raeburn  14969: =item * 
                   14970: 
1.1172.2.35  raeburn  14971: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   14972: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14973: the target domain.
                   14974: 
                   14975: May also include additional key => value pairs for the following groups:
                   14976: 
                   14977: =over
                   14978: 
                   14979: =item
                   14980: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14981: 
                   14982: =over
                   14983: 
                   14984: =item defaultquota, authorquota
                   14985: 
                   14986: =back
                   14987: 
                   14988: =item
                   14989: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14990: portfolio for users).
                   14991: 
                   14992: =over
                   14993: 
                   14994: =item
                   14995: aboutme, blog, webdav, portfolio
                   14996: 
                   14997: =back
                   14998: 
                   14999: =item
                   15000: requestcourses: ability to request courses, and how requests are processed.
                   15001: 
                   15002: =over
                   15003: 
                   15004: =item
1.1172.2.37  raeburn  15005: official, unofficial, community, textbook
1.1172.2.35  raeburn  15006: 
                   15007: =back
                   15008: 
                   15009: =item
                   15010: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15011: 
                   15012: =over
                   15013: 
                   15014: =item
1.1172.2.44  raeburn  15015: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15016: 
                   15017: =back
                   15018: 
                   15019: =item
                   15020: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15021: for course's uploaded content.
                   15022: 
                   15023: =over
                   15024: 
                   15025: =item
1.1172.2.68  raeburn  15026: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15027: communityquota, textbookquota
1.1172.2.35  raeburn  15028: 
                   15029: =back
                   15030: 
                   15031: =item
                   15032: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15033: on your servers.
                   15034: 
                   15035: =over
                   15036: 
                   15037: =item
                   15038: remotesessions, hostedsessions
                   15039: 
                   15040: =back
                   15041: 
                   15042: =back
                   15043: 
                   15044: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15045: utility to create a configuration.db file on a domain's primary library server
                   15046: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15047: -- corresponding values are authentication type (internal, krb4, krb5,
                   15048: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15049: will be available. Values are retrieved from cache (if current), unless the
                   15050: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15051: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15052: 
                   15053: Typical usage:
1.943     raeburn  15054: 
1.1172.2.35  raeburn  15055: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15056: 
1.243     albertel 15057: =back
                   15058: 
                   15059: =head2 Network Status Functions
                   15060: 
                   15061: =over 4
1.191     harris41 15062: 
                   15063: =item *
                   15064: 
1.1137    raeburn  15065: dirlist() : return directory list based on URI (first arg).
                   15066: 
                   15067: Inputs: 1 required, 5 optional.
                   15068: 
                   15069: =over
                   15070: 
                   15071: =item 
                   15072: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15073: 
                   15074: =item
                   15075: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15076: 
                   15077: =item
                   15078: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15079: 
                   15080: =item
                   15081: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15082: 
                   15083: =item
                   15084: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15085: 
                   15086: =item 
                   15087: $alternateRoot - path to prepend in place of path from $uri.
                   15088: 
                   15089: =back
                   15090: 
                   15091: Returns: Array of up to two items.
                   15092: 
                   15093: =over
                   15094: 
                   15095: a reference to an array of files/subdirectories
                   15096: 
                   15097: =over
                   15098: 
                   15099: Each element in the array of files/subdirectories is a & separated list of
                   15100: item name and the result of running stat on the item.  If dirlist was requested
                   15101: for a file instead of a directory, the item name will be ''. For a directory 
                   15102: listing, if the item is a metadata file, the element will end &N&M 
                   15103: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15104: default copyright set (1).  
                   15105: 
                   15106: =back
                   15107: 
                   15108: a scalar containing error condition (if encountered).
                   15109: 
                   15110: =over
                   15111: 
                   15112: =item 
                   15113: no_host (no homeserver identified for $username:$domain).
                   15114: 
                   15115: =item 
                   15116: no_such_host (server contacted for listing not identified as valid host).
                   15117: 
                   15118: =item 
                   15119: con_lost (connection to remote server failed).
                   15120: 
                   15121: =item 
                   15122: refused (invalid $username:$domain received on lond side).
                   15123: 
                   15124: =item 
                   15125: no_such_dir (directory at specified path on lond side does not exist). 
                   15126: 
                   15127: =item 
                   15128: empty (directory at specified path on lond side is empty).
                   15129: 
                   15130: =over
                   15131: 
                   15132: This is currently not encountered because the &ls3, &ls2, 
                   15133: &ls (_handler) routines on the lond side do not filter out
                   15134: . and .. from a directory listing. 
                   15135: 
                   15136: =back
                   15137: 
                   15138: =back
                   15139: 
                   15140: =back
1.191     harris41 15141: 
                   15142: =item *
                   15143: 
1.243     albertel 15144: spareserver() : find server with least workload from spare.tab
                   15145: 
1.986     foxr     15146: 
                   15147: =item *
                   15148: 
                   15149: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15150: if there is no corresponding loncapa host.
                   15151: 
1.243     albertel 15152: =back
                   15153: 
1.986     foxr     15154: 
1.243     albertel 15155: =head2 Apache Request
                   15156: 
                   15157: =over 4
1.191     harris41 15158: 
                   15159: =item *
                   15160: 
1.243     albertel 15161: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15162: localhost, posts hash
                   15163: 
                   15164: =back
                   15165: 
                   15166: =head2 Data to String to Data
                   15167: 
                   15168: =over 4
1.191     harris41 15169: 
                   15170: =item *
                   15171: 
1.243     albertel 15172: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15173: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15174: 
                   15175: =item *
                   15176: 
1.243     albertel 15177: hashref2str($hashref) : convert a hashref into a string complete with
                   15178: escaping and '=' and '&' separators, supports elements that are
                   15179: arrayrefs and hashrefs
1.191     harris41 15180: 
                   15181: =item *
                   15182: 
1.243     albertel 15183: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15184: with escaping and '&' separators, supports elements that are arrayrefs
                   15185: and hashrefs
1.191     harris41 15186: 
                   15187: =item *
                   15188: 
1.243     albertel 15189: str2hash($string) : convert string to hash using unescaping and
                   15190: splitting on '=' and '&', supports elements that are arrayrefs and
                   15191: hashrefs
1.191     harris41 15192: 
                   15193: =item *
                   15194: 
1.243     albertel 15195: str2array($string) : convert string to hash using unescaping and
                   15196: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15197: 
                   15198: =back
                   15199: 
                   15200: =head2 Logging Routines
                   15201: 
                   15202: 
                   15203: These routines allow one to make log messages in the lonnet.log and
                   15204: lonnet.perm logfiles.
1.191     harris41 15205: 
1.1119    foxr     15206: =over 4
                   15207: 
1.191     harris41 15208: =item *
                   15209: 
1.243     albertel 15210: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15211: 
                   15212: =item *
                   15213: 
1.243     albertel 15214: logthis() : append message to the normal lonnet.log file, it gets
                   15215: preiodically rolled over and deleted.
1.191     harris41 15216: 
                   15217: =item *
                   15218: 
1.243     albertel 15219: logperm() : append a permanent message to lonnet.perm.log, this log
                   15220: file never gets deleted by any automated portion of the system, only
                   15221: messages of critical importance should go in here.
                   15222: 
1.1119    foxr     15223: 
1.243     albertel 15224: =back
                   15225: 
                   15226: =head2 General File Helper Routines
                   15227: 
                   15228: =over 4
1.191     harris41 15229: 
                   15230: =item *
                   15231: 
1.481     raeburn  15232: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15233: (a) files in /uploaded
                   15234:   (i) If a local copy of the file exists - 
                   15235:       compares modification date of local copy with last-modified date for 
                   15236:       definitive version stored on home server for course. If local copy is 
                   15237:       stale, requests a new version from the home server and stores it. 
                   15238:       If the original has been removed from the home server, then local copy 
                   15239:       is unlinked.
                   15240:   (ii) If local copy does not exist -
                   15241:       requests the file from the home server and stores it. 
                   15242:   
                   15243:   If $caller is 'uploadrep':  
                   15244:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15245:     for request for files originally uploaded via DOCS. 
                   15246:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15247:   
                   15248:   Otherwise:
                   15249:      This indicates a call from the content generation phase of the request.
                   15250:      -  returns the entire contents of the file or -1.
                   15251:      
                   15252: (b) files in /res
                   15253:    - returns the entire contents of a file or -1; 
                   15254:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15255: 
1.712     albertel 15256: 
                   15257: =item *
                   15258: 
                   15259: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15260:                   reference
                   15261: 
                   15262: returns either a stat() list of data about the file or an empty list
                   15263: if the file doesn't exist or couldn't find out about it (connection
                   15264: problems or user unknown)
                   15265: 
1.191     harris41 15266: =item *
                   15267: 
1.243     albertel 15268: filelocation($dir,$file) : returns file system location of a file
                   15269: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15270: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15271: and a file of ../bob will become /a/bob)
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
                   15275: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15276: filelocation except for hrefs
                   15277: 
                   15278: =item *
                   15279: 
1.1172.2.49  raeburn  15280: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15281: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15282: 
1.243     albertel 15283: =back
                   15284: 
1.608     albertel 15285: =head2 Usererfile file routines (/uploaded*)
                   15286: 
                   15287: =over 4
                   15288: 
                   15289: =item *
                   15290: 
                   15291: userfileupload(): main rotine for putting a file in a user or course's
                   15292:                   filespace, arguments are,
                   15293: 
1.620     albertel 15294:  formname - required - this is the name of the element in $env where the
1.608     albertel 15295:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15296:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15297:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15298:  context - if coursedoc, store the file in the course of the active role
                   15299:              of the current user; 
                   15300:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15301:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15302:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15303:          if undefined, it will be placed in "unknown"
                   15304: 
                   15305:  (This routine calls clean_filename() to remove any dangerous
                   15306:  characters from the filename, and then calls finuserfileupload() to
                   15307:  complete the transaction)
                   15308: 
                   15309:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15310:  and /adm/notfound.html if unsuccessful
                   15311: 
                   15312: =item *
                   15313: 
                   15314: clean_filename(): routine for cleaing a filename up for storage in
                   15315:                  userfile space, argument is:
                   15316: 
                   15317:  filename - proposed filename
                   15318: 
                   15319: returns: the new clean filename
                   15320: 
                   15321: =item *
                   15322: 
1.1090    raeburn  15323: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15324: userspace, probably shouldn't be called directly
                   15325: 
                   15326:   docuname: username or courseid of destination for the file
                   15327:   docudom: domain of user/course of destination for the file
                   15328:   formname: same as for userfileupload()
1.1090    raeburn  15329:   fname: filename (including subdirectories) for the file
                   15330:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15331:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15332:   allfiles: reference to hash used to store objects found by parser
                   15333:   codebase: reference to hash used for codebases of java objects found by parser
                   15334:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15335:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15336:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15337:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15338:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15339:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15340:   mimetype: reference to scalar to accommodate mime type determined
                   15341:             from File::MMagic if $parser = parse.
1.608     albertel 15342: 
                   15343:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15344:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15345:  was 'overwrite').
                   15346:  
1.608     albertel 15347: 
                   15348: =item *
                   15349: 
                   15350: renameuserfile(): renames an existing userfile to a new name
                   15351: 
                   15352:   Args:
                   15353:    docuname: username or courseid of destination for the file
                   15354:    docudom: domain of user/course of destination for the file
                   15355:    old: current file name (including any subdirs under userfiles)
                   15356:    new: desired file name (including any subdirs under userfiles)
                   15357: 
                   15358: =item *
                   15359: 
                   15360: mkdiruserfile(): creates a directory is a userfiles dir
                   15361: 
                   15362:   Args:
                   15363:    docuname: username or courseid of destination for the file
                   15364:    docudom: domain of user/course of destination for the file
                   15365:    dir: dir to create (including any subdirs under userfiles)
                   15366: 
                   15367: =item *
                   15368: 
                   15369: removeuserfile(): removes a file that exists in userfiles
                   15370: 
                   15371:   Args:
                   15372:    docuname: username or courseid of destination for the file
                   15373:    docudom: domain of user/course of destination for the file
                   15374:    fname: filname to delete (including any subdirs under userfiles)
                   15375: 
                   15376: =item *
                   15377: 
                   15378: removeuploadedurl(): convience function for removeuserfile()
                   15379: 
                   15380:   Args:
                   15381:    url:  a full /uploaded/... url to delete
                   15382: 
1.747     albertel 15383: =item * 
                   15384: 
                   15385: get_portfile_permissions():
                   15386:   Args:
                   15387:     domain: domain of user or course contain the portfolio files
                   15388:     user: name of user or num of course contain the portfolio files
                   15389:   Returns:
                   15390:     hashref of a dump of the proper file_permissions.db
                   15391:    
                   15392: 
                   15393: =item * 
                   15394: 
                   15395: get_access_controls():
                   15396: 
                   15397: Args:
                   15398:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15399:   group: (optional) the group you want the files associated with
                   15400:   file: (optional) the file you want access info on
                   15401: 
                   15402: Returns:
1.749     raeburn  15403:     a hash (keys are file names) of hashes containing
                   15404:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15405:         values are XML containing access control settings (see below) 
1.747     albertel 15406: 
                   15407: Internal notes:
                   15408: 
1.749     raeburn  15409:  access controls are stored in file_permissions.db as key=value pairs.
                   15410:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15411:         where scope -> public,guest,course,group,domains or users.
                   15412:               end -> UNIX time for end of access (0 -> no end date)
                   15413:               start -> UNIX time for start of access
                   15414: 
                   15415:     value -> XML description of access control
                   15416:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15417:             <start></start>
                   15418:             <end></end>
                   15419: 
                   15420:             <password></password>  for scope type = guest
                   15421: 
                   15422:             <domain></domain>     for scope type = course or group
                   15423:             <number></number>
                   15424:             <roles id="">
                   15425:              <role></role>
                   15426:              <access></access>
                   15427:              <section></section>
                   15428:              <group></group>
                   15429:             </roles>
                   15430: 
                   15431:             <dom></dom>         for scope type = domains
                   15432: 
                   15433:             <users>             for scope type = users
                   15434:              <user>
                   15435:               <uname></uname>
                   15436:               <udom></udom>
                   15437:              </user>
                   15438:             </users>
                   15439:            </scope> 
                   15440:               
                   15441:  Access data is also aggregated for each file in an additional key=value pair:
                   15442:  key -> path to file/file_name\0accesscontrol 
                   15443:  value -> reference to hash
                   15444:           hash contains key = value pairs
                   15445:           where key = uniqueID:scope_end_start
                   15446:                 value = UNIX time record was last updated
                   15447: 
                   15448:           Used to improve speed of look-ups of access controls for each file.  
                   15449:  
                   15450:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15451: 
1.1172.2.13  raeburn  15452: =item *
                   15453: 
1.749     raeburn  15454: modify_access_controls():
                   15455: 
                   15456: Modifies access controls for a portfolio file
                   15457: Args
                   15458: 1. file name
                   15459: 2. reference to hash of required changes,
                   15460: 3. domain
                   15461: 4. username
                   15462:   where domain,username are the domain of the portfolio owner 
                   15463:   (either a user or a course) 
                   15464: 
                   15465: Returns:
                   15466: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15467: 2. result of deletions ('ok' or 'error', with error message).
                   15468: 3. reference to hash of any new or updated access controls.
                   15469: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15470:    key = integer (inbound ID)
1.1172.2.13  raeburn  15471:    value = uniqueID
                   15472: 
                   15473: =item *
                   15474: 
                   15475: get_timebased_id():
                   15476: 
                   15477: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15478: course via the Course Editor (e.g., folders, composite pages,
                   15479: group bulletin boards).
                   15480: 
                   15481: Args: (first three required; six others optional)
                   15482: 
                   15483: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15484:    docssequence, or name of group
                   15485: 
                   15486: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15487:    e.g., num, boardids
                   15488: 
                   15489: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15490:    file will be named nohist_namespace.db
                   15491: 
                   15492: 4. cdom: domain of course; default is current course domain from %env
                   15493: 
                   15494: 5. cnum: course number; default is current course number from %env
                   15495: 
                   15496: 6. idtype: set to concat if an additional digit is to be appended to the
                   15497:    unix timestamp to form the suffix, if the plain timestamp is already
                   15498:    in use.  Default is to not do this, but simply increment the unix
                   15499:    timestamp by 1 until a unique key is obtained.
                   15500: 
                   15501: 7. who: holder of locking key; defaults to user:domain for user.
                   15502: 
                   15503: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15504:    retrying); default is 3.
                   15505: 
                   15506: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15507: 
                   15508: Returns:
                   15509: 
                   15510: 1. suffix obtained (numeric)
                   15511: 
                   15512: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15513: 
                   15514: 3. error: contains (localized) error message if an error occurred.
                   15515: 
1.747     albertel 15516: 
1.608     albertel 15517: =back
                   15518: 
1.243     albertel 15519: =head2 HTTP Helper Routines
                   15520: 
                   15521: =over 4
                   15522: 
1.191     harris41 15523: =item *
                   15524: 
                   15525: escape() : unpack non-word characters into CGI-compatible hex codes
                   15526: 
                   15527: =item *
                   15528: 
                   15529: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15530: 
1.243     albertel 15531: =back
                   15532: 
                   15533: =head1 PRIVATE SUBROUTINES
                   15534: 
                   15535: =head2 Underlying communication routines (Shouldn't call)
                   15536: 
                   15537: =over 4
                   15538: 
                   15539: =item *
                   15540: 
                   15541: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15542: 
                   15543: =item *
                   15544: 
                   15545: reply() : uses subreply to send a message to remote machine, logs all failures
                   15546: 
                   15547: =item *
                   15548: 
                   15549: critical() : passes a critical message to another server; if cannot
                   15550: get through then place message in connection buffer directory and
                   15551: returns con_delayed, if incapable of saving message, returns
                   15552: con_failed
                   15553: 
                   15554: =item *
                   15555: 
                   15556: reconlonc() : tries to reconnect lonc client processes.
                   15557: 
                   15558: =back
                   15559: 
                   15560: =head2 Resource Access Logging
                   15561: 
                   15562: =over 4
                   15563: 
                   15564: =item *
                   15565: 
                   15566: flushcourselogs() : flush (save) buffer logs and access logs
                   15567: 
                   15568: =item *
                   15569: 
                   15570: courselog($what) : save message for course in hash
                   15571: 
                   15572: =item *
                   15573: 
                   15574: courseacclog($what) : save message for course using &courselog().  Perform
                   15575: special processing for specific resource types (problems, exams, quizzes, etc).
                   15576: 
1.191     harris41 15577: =item *
                   15578: 
                   15579: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15580: as a PerlChildExitHandler
1.243     albertel 15581: 
                   15582: =back
                   15583: 
                   15584: =head2 Other
                   15585: 
                   15586: =over 4
                   15587: 
                   15588: =item *
                   15589: 
                   15590: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15591: 
                   15592: =back
                   15593: 
                   15594: =cut
1.877     foxr     15595: 

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